How to Communicate Using TCP/IP In Java

Share and Enjoy !

TCP/Ip communication is based on client server model. It allows bi directional,point to point ,stream based connection between two machines one of which is termed as server and other of the two machine is termed as client. This is implemented using two core classes
1. Socket–read here
2. ServerSocket–read here
These two classes establishes socket connection between client and server. Sockets in java are end points of communication links between processes(Which are under execution in two machines).The socket class is to create a socket for the client and Socket server is for server.
Once the socket object is created , then it can gain access to the input and output streams associated with it.Similar to socket class ServerSocket class creates a Socket connection for the server.
The communication is simplified as:

Sl NoClientCommunicationServer
Attempts to connect
ServerSocket(port,count)Register with this service and wait for connection
//Socket to initiate a commucation

Port number can be of range 0 to 65535 uniquely but 0-1023 is reserved for standard internet port.
The simple TCP/IP connection code is given as below:

class MysimpleServer{
public static void main(String args[])
ServerSocket server;
Socket socket;
String Message="Hello";
OutputStream oStream;
DataOutputStream dataOut;
server=new ServerSocket(9876);
catch(IOException e){}
socket=server.accept();//waits here and listen for a connaction
dataOut=new DataOutputStream();
dataOut.close();//closes the data object when message is sent.
oStream.close();//closes the output stream on the current socket.
socket.close();//closes the current socket connection
catch(IOException e){}
//listen to the other clients

DataOutputStream is used to send message in binary bit String format to portability.The writeUTF(String) is a function defined in DataOutputStream class to write a String Object.
The client code is as follows:

class MySimpleClient{
public static void main(String args[])
int c;
Socket socket;
InputStream inputStream;
DataInputStreram dataIn;
socket=new Socket("New Server",9876);
//create a socket to connect the server "New server at port 9876"
dataIn=new DataInputStream(inputStream);
//get an input stream in binary
String msg=new String(dataIn.readUTF());
//read the input stream.

client will connect the machine with a server called new Server having machine id 9876 as port no. If server sends some message,it will be displayed on client.

READ  JSoup A Nice Initiative To Fetch Information From HTML

Share and Enjoy !

One thought on “How to Communicate Using TCP/IP In Java

  1. Pingback: Why You Must Experience VPN At Least Once In Your Lifetime? - Tech Travel Hub

Leave a Reply

Your email address will not be published. Required fields are marked *