Socket Programming in Java

This article describes a very basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection. There’s a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of that, making network programming very easy for programmers.

Client-Side Programming

Establish a Socket Connection

To connect to another machine we need a socket connection. A socket connection means the two machines have information about each other’s network location (IP Address) and TCP port. The java.net.Socket class represents a Socket. To open a socket:

Socket socket = new Socket(“127.0.0.1”, 5000)

Communication
To communicate over a socket connection, streams are used to both input and output the data.

Closing the connection

The socket connection is closed explicitly once the message to the server is sent.

In the program, the Client keeps reading input from a user and sends it to the server until “Over” is typed.

Java Implementation