Over a million developers have joined DZone.

Socket Communication in Client/Server Relationship

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

When writing java code for a Client or Server, using Sockets are the most efficient way to communicate between the client and server.  Sockets are flexible, sufficient, easy to implement, and they do not use a lot of network traffic.

There are many reasons why your client/server may not be connecting to each other:

  • Make sure you import “java.net”
  • Make sure the socket is bound to a port number
  • Make sure you have the correct IP address
  • Make sure the socket for the server accepts the right port number

In Java, the client initiates the connection by instantiating a Socket.  The Socket constructor usually takes in two parameters: TCP/IP address of the server and port number of the application.  After the client instantiates the Socket, the client will instantiate DataInputStream and DataOutputStream.  These high-level classes share the same Socket.  The client will wait for the server to accept the connection.

How to code this in Java:

Socket s = new Socket(serverAddress, 1234); //connect to server app
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
String answer = dis.readUTF(); //wait for reply
The Server application uses a “ServerSocket” class and the constructor takes the port number as a parameter.  If you are an application programmer on the server, you would need to get a port number from the administrator.  When you call accept method, the server application waits for the client to call the port number.  After the ServerSocket accepts the client, it negotiates with the client to switch to an available port so that the main port is still open for other clients to connect to the server.  The server will wait for the client to say something and each client will spend its time waiting in a readUTF method.

How to code this in Java:
Socket s = ss.accept(); // wait for a client connection
DataInputStream dis = new DataInputStream (s.getInputStream());
DataOutputStream dos = new DataOutputStream (s.getOutputStream());
String question = dis.readUTF();

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}