Java socket programming

What is socket? Explain the features of socket.

1. Socket is a combination of ip address and port number

2. Client sends request to the server by using server’s ip address and the corresponding port number

3. Java has java.net.Socket class to communicate through socket

4. A socket allows to perform 4 fundamental socket operations:
a. Connecting to remote systems
b. Sending data to the nodes in the network
c. Receiving data from the server
d. Closing connection to the server

5. Every socket is associated with only one remote host.

6. Data is sent and received through byte oriented streams. The getOutputStream() is utilized to place the request and getInputStream() is utilized to receive response.

7. The following are the methods to return the information about the socket:
a. public InetAddress getInetAddress() – to obtain the ip address
b. public int getPort() – to obtain the port

Explain the characteristics of Java socket class.

The following are certain characteristics that socket share:

1. The socket is available as long as the network process maintains an open link to the socket
2. A socket can be named in order to communicate with other sockets in a network
3. Communication is performed by the sockets in network when the server receives the connections and requests from them.
4. Messages can also be shared between a client and the server
5. Pairs of sockets can be created. However, this is possible in the AF_UNIX address family

Explain ServerSocket class with an example

1. A ServerSocket waits for the requests from the clients in a network
2. It is constructed on a specific port for sending responses.
3. The accept() method is used to receive the requests an returns java.net.Socket objects

- Following are the constructors of ServerSocket class:

a. public ServerSocket(int port) throws IOException
b. public ServerSocket(int port, int backlog) throws IOException
c. public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException

The following code snippet creates a ServerSocket object and waits for requests from client
int portNo = 12000;
// creates server socket object in server program
ServerSocket serSocket = new ServerSocket(portNo);
// Waits for connection from client
Socket socket = serSocket.accept();
Following is the complete server program:
// SimpleServer.java: a simple server program
import java.net.*;
import java.io.*;
public class ServerExample
{
   public void reqResponse() throws IOException
   {
       // Register service on port 6700
       ServerSocket srvSkt = new ServerSocket(6700);
       System.out.println("Server started...!!");
       while(true)
       {
           Socket skt=srvSkt.accept();
           // Wait and accept a connection // Get a communication stream associated with the socket
           OutputStream outStream = skt.getOutputStream();
           DataOutputStream dos = new DataOutputStream (outStream);
           // Send a message
           dos.writeUTF("Hi there");
           // Close the connection, but not the server socket
           outStream.close();
           skt.close(); // Client connection closed
       }
   }
}

Explain InetAddress class with an example

1. InetAddress is a class that represents an Internet Protocol address
2. Link-local, Site local and Global addresses are the scope for InetAddress class
3. The method getByName() returns the host details.
4. The method getHostName() returns the name of the host system
5. The method getHostAdress() returns the ip address of the host system

The following is the code snippet that depicts the use of InetAddress
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressExample
{
   // This method performs a NS Lookup
   public void performNSLookup()
   {
   try
   {
       InetAddress inetHost = InetAddress.getByName("yoursite.com");
       String hostName = inetHost.getHostName();
       System.out.println("The host name was: " + hostName);
       System.out.println("The hosts IP address is: " + inetHost.getHostAddress());
   }
   catch(UnknownHostException ex)
   {
       System.out.println("Unrecognized host");
   }
   }
}

Explain DatagramSocket class with an example

1. A socket is represented by DatagramSocket for sending and receiving datagram packets.

2. Every packet sent or received on this socket is addressed and routed individually.

3. The packets sent from system to system might by routed differently and may arrive in any order.

4. DatagramSocket broadcasts on User Datagram Packet.

Example:
DatagramSocket dgSkt = new DatagramSocket(null);
dgSkt.bind(new InetSocketAddress(8362));
Following is the code example illustrates the use of DatagramSocket
//PROGRAM FOR SERVER SIDE

import java.io.*;

import java.net.*;
import java.util.*;

public class Receive
{
   public static void main(String args[])throws Exception
   {
       DatagramSocket socket = null;
       socket = new DatagramSocket(5478);
       for (int index = 0; index < 10; index++)
       {
           byte[] buf = new byte[256];
           DatagramPacket packet = new DatagramPacket(buf, buf.length);
           socket.receive(packet);
           buf = new Date().toString().getBytes();
           InetAddress address = packet.getAddress();
           int port = packet.getPort(); // retrieves the port number
           packet = new DatagramPacket(buf, buf.length, address, port);
           socket.send(packet); // sends packets
       }
           socket.close();
   }
}

//PROGRAM FOR CLIENT SIDE

import java.io.*;
import java.net.*;

public class send
{
   public static void main(String[] args) throws Exception
   {
       DatagramSocket socket = new DatagramSocket();
       for (int index = 0; index < 10; index++)
       {
           byte[] buf = new byte[256];
           InetAddress address = InetAddress.getByName("localhost");
           //localhost can be replaced by ipaddress of the server

           packet = new DatagramPacket(buf, buf.length);
           socket.receive(packet);
           String received = new String(packet.getData());
           System.out.println("Time of server " + received);
           Thread.sleep(1500);
       }
           socket.close();
   }
}

Explain DatagramPacket class with an example

1. DatagramPacket contains data that is to be transmitted to the destination, destination address.
2. Datagram packets are sent by non-establishing a circuit like a virtual circuit switching networks
3. It contains the address and the port number to which the packet should send
4. Being it transmit data on UDP, it is not ensure the reliability of packets delivery to the destination.

Code example for illustrating the use of DatagramPacket Server
import java.net.*;
import java.io.*;

public class ServerPacket
{
   public static void main(String args[])
   {
       DatagramSocket dgmSocket = null;
       try
       {
           dgmSocket = new DatagramSocket(6788);
           String str = "Hello! This is Server calling you";
           byte[] bmsg = str.getBytes();
           DatagramPacket dgpkt = new DatagramPacket(bmsg, bmsg.length);
           byte[] buffer = new byte[1000];
           while (true)
           {
               DatagramPacket request = new DatagramPacket(buffer, buffer.length);
               dgmSocket.receive(request);
               DatagramPacket reply = new DatagramPacket(dgpkt.getaData(), dgpkt.getLength(),
               request.getAddress(), request.getPort());
               dgmSocket.send(reply);
           }
       }
           dgmSocket.close();
}
Code example for illustrating the use of DatagramPacket Client
import java.net.*;
import java.io.*;

public class ClientSocket
{
   public static void main(String args[])
   {
       DatagramSocket dgmSocket = null;

       dgmSocket = new DatagramSocket(6788);
       String str = "Hello This is Client";
       byte[] bmsg = str.getBytes();
       DatagramPacket dgmpkt = new DatagramPacket(bmsg, bmsg.length);
       byte[] buffer = new byte[1000];
       while (true)
       {
           DatagramPacket request = new DatagramPacket(buffer, buffer.length);
           dgmSocket.receive(request);
           DatagramPacket reply = new DatagramPacket(dgmSocket.getData(), dgmSocket.getLength(),request.getAddress(), request.getPort());
           dgmSocket.send(reply);
       }
           dgmSocket.close();
   }
}
JDBC
JDBC - Purposes of JDBC API, Describe 4 types of JDBC drivers and their characteristics with usages, State the functionalities of important classes in JDBC packages, Explain how to use JDBC statement to execute SQL queries...
Two String objects with same values not to be equal under the == operator.
The == operator compares references and not contents. It compares two objects and if they are the same object in memory and present in the same memory location...
Static in java
Static variables are declared with the static keyword in a class, Static variables are always called by the class name...
Post your comment