Tag Archives: Socket

Designing a basic chat system using Java Socket programming

“A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. “  – Oracle Docs.

So,

Server Socket  listens to  port    ==>     <XX>    <==     Client Socket connect to port

Lets build a basic chat system using socket programming.

Server Socket : It listens to port 2200 and responds to client

package com.language.sockets;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

// This is Server Socket which listens to and responds to client
public class ServerSocketImpl {

    public static void main(String args[])
    {
        ServerSocket server = null;
        Socket  client = null;
        InputStream instream = null;
        Scanner scanner = null;
       OutputStream oos= null;
        try {
            server = new ServerSocket(2200, 10, InetAddress.getByName("localhost"));
            System.out.println("Listening to port 2200");
            client = server.accept();
            scanner = new Scanner(System.in);
            while(true)
            {
                instream = client.getInputStream();
                oos = client.getOutputStream();
                byte b[] = new byte[1024];
                int read = 0;
                if((read = instream.read(b)) > 0)
                {
                    System.out.println("New Chat : " + new String(b));
                }

                if(scanner.hasNext())
                {
                    oos.write(scanner.nextLine().getBytes());
                }

            }
        }
        catch(UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally {
            if(server != null)
            {
                try
                {
                    server.close();
                }
                catch(IOException e)
                {}
            }
            if(client!=null)
            {
                try
                {
                    client.close();
                }
                catch(IOException e)
                {

                }
            }
            if(instream!=null)
            {
                try
                {
                    instream.close();
                }
                catch(IOException e)
                {

                }
            }
        }
    }
}

Client Socket : It connects to port 2200 and responds to server

package com.language.sockets;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ServerClientImpl {
    public static void main(String args[])
    {
        OutputStream oos = null;
        Socket client = null;
        Scanner scanner = null;
        InputStream is = null;
        try {
            client = new Socket(InetAddress.getByName("localhost"), 2200);
            oos = client.getOutputStream();
            scanner = new Scanner(System.in);
            is =   client.getInputStream();
            while(true)
            {
                if(scanner.hasNext())
                {
                    oos.write(scanner.nextLine().getBytes());
                    oos.flush();
                }
                int read = 0;
                byte b[] = new byte[1024];
                if((read = is.read(b)) > 0)
                {
                    System.out.println(new String(b));
                }
            }
        }
        catch(UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally {
            if(oos != null)
            {
                try
                {
                    oos.close();
                }
               catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client!=null)
            {
                try {
                    client.close();
                }
                catch(IOException e)
                {}
            }
            if(scanner !=null)
            {
                scanner.close();
            }
        }
    }
}

Now compile the classes and open two command prompts one for the Server and another for client and exchange the message (Communication should start from the Client) :

Window 1 : 

C:\Test>java com.language.sockets.ServerSocketImpl

Listening to port 2200

sHello Server
Hi ClientProgram

Window 2 : 

C:\Test>java com.language.sockets.ServerClientImpl

Hello Server
Hi ClientProgram

 

Happy Coding 🙂

Advertisements