By kswaughs | Thursday, December 10, 2015

Java socket programming

Java Socket programming is used to communicate between the applications that are running on different machines. A server program runs on a server machine listening with a provided port number. A client program connects to the server program through java.net.Socket class by providing IpAddress and port. Once the connection is established, client sends the message to the server and server receives the message. The communication can be happen either one-way or two-way.

Below are the examples of Server and Client programs for both ways of communication.

  • One way communication : Client -> Server
  • Two way communication : Client <-> Server

One way communication

Server program which keeps listening to receive the messages on a specific port.

Server.java
package com.kswaughs.socket;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Server extends Thread {

    private ServerSocket serverSocket;
 
    public Server(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void run() {
        while (true) {
            try {
    
                System.out.println("I am Server, Waiting for a client request on port " 
                    + serverSocket.getLocalPort());
    
                Socket server = serverSocket.accept();
    
                // Read input message from client
                DataInputStream in = new DataInputStream(server.getInputStream());
                String inputData = in.readUTF();
                System.out.println("Request Data:"+ inputData);
    
                server.close();
 
            } catch (SocketTimeoutException s) {
                System.out.println("Socket timed out!");
                break;
            } catch (IOException e) {
                e.printStackTrace();
                break;
            } finally {
                System.out.println("\n********** end **********\n");
            }
        }
    }

    public static void main(String[] args) {

        try {
            Thread t = new Server(1234);
            t.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client program which sends message to a server.

Client.java
package com.kswaughs.socket;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client {

    public static void main(String[] args) {

        try {
            String serverName = InetAddress.getLocalHost().getHostAddress();
            int port = 1234;

            Socket client = new Socket(serverName, port);

            // Send message to server
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            out.writeUTF("Hello Server, This is my first request..");

            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Server logs:

I am Server, Waiting for a client request on port 1234
Request Data:Hello Server, This is my first request..

********** end **********

I am Server, Waiting for a client request on port 1234

Two way communication

Server program which keeps listening to receive the messages on a specific port and acknowledges back with the status of the request.

Server.java
package com.kswaughs.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Server extends Thread {

    private ServerSocket serverSocket;
 
    public Server(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void run() {
        while (true) {
            try {

                System.out.println("I am Server, Waiting for a client request on port " 
                    + serverSocket.getLocalPort());
    
                Socket server = serverSocket.accept();
    
                // Read input message from client
                DataInputStream in = new DataInputStream(server.getInputStream());
                String inputData = in.readUTF();
                System.out.println("Request Data:"+ inputData);
    
                // Send output message to client
                OutputStream outToServer = server.getOutputStream();
                DataOutputStream out = new DataOutputStream(outToServer);
                out.writeUTF("Your request processed successfully");
    
                server.close();
 
            } catch (SocketTimeoutException s) {
                System.out.println("Socket timed out!");
                break;
            } catch (IOException e) {
                e.printStackTrace();
                break;
            } finally {
                System.out.println("\n********** end **********\n");
            }
        }
    }

    public static void main(String[] args) {

        try {
            Thread t = new Server(1234);
            t.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client program which sends message to a server and receives the acknowledgement from the server.

Client.java
package com.kswaughs.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client {

    public static void main(String[] args) {

        try {
            String serverName = InetAddress.getLocalHost().getHostAddress();
            int port = 1234;

            Socket client = new Socket(serverName, port);

            // Send message to server
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            out.writeUTF("Hello Server, This is my second request..");
   
            // Receive message from server
            DataInputStream in = new DataInputStream(client.getInputStream());
            String respData = in.readUTF();
            System.out.println("Response Data:"+ respData);

            client.close();
   
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

server logs

I am Server, Waiting for a client request on port 1234
Request Data:Hello Server, This is my second request..

********** end **********

I am Server, Waiting for a client request on port 1234

client logs

Response Data:Your request processed successfully

Recommend this on


No comments:

Post a Comment