Coders Packet

Java program to create Server/Client Chat Application

By Gaurav Dhavala

Using Socket programming we will communicate between server and client using different JRE.

Hi, here we will learn how to use Sockets in JAVA programming and implementing it to communicate between client and server.

Socket Programming

Socket programming is used to make a connection between two nodes namely server and client on a network. By using this we can create a two-way connection between multiple nodes. 

Logic

1) Firstly we will use sockets to request a connection between the nodes by passing the port number and keeping the host as localhost.

2) Once the server accepts the connection, we will implement a Runnable interface and override its methods to display the messages between the nodes.

3) We have used ExecutorService to create a thread pool and to connect multiple clients with the server at a time.   

4) We will be using Threads to handle multiple messages from clients at a time.

5) Once the message "bye" is sent by any node our program will stop. 

Codes

For Server

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class S_Class {
    int pt;
    ServerSocket ss = null;
    Socket socket = null;
    ExecutorService es = null;
    int clientcount = 0;

    public static void main(String[] args) throws IOException {
        S_Class sObject = new S_Class(5000);
        sObject.startServer();
    }

    S_Class(int pt) {
        this.pt = pt;
        es = Executors.newFixedThreadPool(5);
    }

    public void startServer() throws IOException {

        ss = new ServerSocket(5000);
        System.out.println("S_Class Started....");
        System.out.println("To break the connection send BYE....");
        while (true) {
            socket = ss.accept();
            clientcount++;
            ServerThread st = new ServerThread(socket, clientcount, this);
            es.execute(st);
        }

    }

    private static class ServerThread implements Runnable {

        S_Class server = null;
        Socket client = null;
        BufferedReader s1;
        PrintStream s2;
        Scanner sc = new Scanner(System.in);
        int id;
        String s;

        ServerThread(Socket client, int count, S_Class server) throws IOException {

            this.client = client;
            this.server = server;
            this.id = count;
            System.out.println("Connection established with client " + id);

            s1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
            s2 = new PrintStream(client.getOutputStream());

        }

        @Override
        public void run() {
            int x = 1;
            try {
                while (true) {
                    s = s1.readLine();

                    System.out.print("Client(" + id + ") : " + s + "\n");
                    System.out.print("S_Class : ");
                    s = sc.nextLine();
                    if (s.equalsIgnoreCase("bye")) {
                        s2.println("BYE");
                        x = 0;
                        System.out.println("Connection Ended....");
                        break;
                    }
                    s2.println(s);
                }

                s1.close();
                client.close();
                s2.close();
                if (x == 0) {
                    System.out.println("*****Closing*****");
                    System.exit(0);
                }
            } catch (IOException e) {
                System.out.println("Error : " + e);
            }
        }
    }
}

 

For Clients

import java.io.*;
import java.net.*;

public class C_Class {

    public static void main(String args[]) throws Exception {
        Socket socket = new Socket("localhost", 5000);
        BufferedReader inputVar = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream outVar = new PrintStream(socket.getOutputStream());
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while (true) {
            System.out.print("Client : ");
            str = stdin.readLine();
            outVar.println(str);
            if (str.equalsIgnoreCase("BYE")) {
                System.out.println("Connection Broken.....");
                break;
            }
            str = inputVar.readLine();
            System.out.print("Server : " + str + "\n");

        }
        socket.close();
        inputVar.close();
        outVar.close();
        stdin.close();
    }

}

 

Output

source- client output

 

 

Download project

Reviews Report

Submitted by Gaurav Dhavala (gauravdhavala)

Download packets of source code on Coders Packet