Over a million developers have joined DZone.

Socket Communication in Client/Server Relationship

DZone's Guide to

Socket Communication in Client/Server Relationship

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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();

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.


Opinions expressed by DZone contributors are their own.

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 }}