Socket Programming in Java
Socket programming in Java enables communication between two devices over a network. It allows data exchange between a client and a server using the java.net package. Sockets serve as communication endpoints, providing the foundation for building distributed applications such as chat systems, file transfer utilities, and client-server applications.
Client-Side Programming
1. Establish a Socket Connection
To connect to another machine we need a socket connection. A socket connection means both machines know each other’s IP address and TCP port. The java.net.Socket class is used to create a socket.
Socket socket = new Socket(“127.0.0.1”, 5000)
- The first argument: The IP address of Server i.e. 127.0.0.1 is the IP address of localhost, where code will run on the single stand-alone machine.
- The second argument: The TCP Port number (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)
2. Communication
To exchange data over a socket connection, streams are used for input and output:
- Input Stream: Reads data coming from the socket.
- Output Stream: Sends data through the socket.
Example to access these streams:
// to read data
InputStream input = socket.getInputStream();
// to send data
OutputStream output = socket.getOutputStream();
3. Closing the Connection
The socket connection is closed explicitly once the message to the server is sent.
Example:
import java.io.*;
import java.net.*;
public class Client {
// Initialize socket and input/output streams
private Socket s = null;
private DataInputStream in = null;
private DataOutputStream out = null;
public Client(String addr, int port)
{
// Establish a connection
try {
s = new Socket(addr, port);
System.out.println("Connected");
// Takes input from terminal
in = new DataInputStream(System.in);
// Sends output to the socket
out = new DataOutputStream(s.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}
// String to read message from input
String m = "";
// Keep reading until "Over" is input
while (!m.equals("Over")) {
try {
m = in.readLine();
out.writeUTF(m);
}
catch (IOException i) {
System.out.println(i);
}
}
// Close the connection
try {
in.close();
out.close();
s.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String[] args) {
Client c = new Client("127.0.0.1", 5000);
}
}
Output
java.net.ConnectException: Connection refused (Connection refused)
Server-Side Programming
1. Establish a Socket Connection
To create a server application two sockets are needed.
ServerSocket: This socket waits for incoming client requests. It listens for connections on a specific port.Socket: Once a connection is established, the server uses this socket to communicate with the client.
2. Communication
- Once the connection is established, you can send and receive data through the socket using streams.
- The getOutputStream() method is used to send data to the client.
3. Close the Connection
Once communication is finished, it's important to close the socket and the input/output streams to free up resources.
Example:
import java.net.*;
import java.io.*;
public class Server {
// Initialize socket and input stream
private Socket s = null;
private ServerSocket ss = null;
private DataInputStream in = null;
// Constructor with port
public Server(int port) {
// Starts server and waits for a connection
try
{
ss = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
s = ss.accept();
System.out.println("Client accepted");
// Takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(s.getInputStream()));
String m = "";
// Reads message from client until "Over" is sent
while (!m.equals("Over"))
{
try
{
m = in.readUTF();
System.out.println(m);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// Close connection
s.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server s = new Server(5000);
}
}
Explanation: In the above example, we have implemented a server that listens on a specific port, accepts a client connection, and reads messages sent by the client. The server displays the messages until "Over" is received, after which it closes the connection and terminates.
Important Points:
- Create a ServerSocket on a specific port (e.g., 5000) to listen for client connections.
- Use accept() to wait for a client; this method blocks until a client connects.
- Obtain the input stream using getInputStream() to read messages from the client.
- Continue reading messages until a termination signal (e.g., "Over") is received.
- Close the client Socket and input stream to terminate the connection.
Run the Application
Open two windows one for Server and another for Client.
1. Run the Server
First run the Server application as:
$ java Server
Output:
Server started
Waiting for a client ...
2. Run the Client
Then run the Client application on another terminal as
$ java Client
Output:
Connected
3. Exchange Messages
- Type messages in the Client window.
- Messages will appear in the Server window.
- Type "Over" to close the connection.
Here is a sample interaction:
Client:
Hello
I made my first socket connection
Over
Server:
Hello
I made my first socket connection
Over
Closing connection
Sending “Over” closes the connection between the Client and the Server just like said before.
Note : If you're using Eclipse or likes of such:
- Compile both of them on two different terminals or tabs
- Run the Server program first
- Then run the Client program
- Type messages in the Client Window which will be received and shown by the Server Window simultaneously.
- Type Over to end.