Pages

Monday, February 27, 2017

Chat Server Socket

Following two socket programs demonstrate basic Chat application. You need to add additional functionalities and exception handling according to your needs.

Chat Server Socket Program

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

public class ChatServer {
    public static void main(String[] args) throws IOException {

        ServerSocket ss = new ServerSocket(1234);
        Socket cs = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Waiting for connection.....");
        cs = ss.accept();      
        BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        PrintWriter out = new PrintWriter(cs.getOutputStream(), true);
        String inputLine, serverInput;
        while(true){
            inputLine = in.readLine();
            System.out.println("Client: " + inputLine);
            System.out.print("Server:");
            serverInput = br.readLine();
            out.println(serverInput);
        }
        out.close();
        in.close();
        cs.close();
        ss.close();
    }
}
//You may add exit condition in while loop of server socket.

Output on server screen:

Waiting for connection.....
Client: hello
Server:hello client
Client: how are you?
Server:I am fine...what about you?


Chat Client Socket Program

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

public class ChatClient {
    public static void main(String[] args) throws IOException
   {
         Socket s1 = new Socket("localhost", 1234);
         DataInputStream is = new DataInputStream(s1.getInputStream());
        // String request = "Hello";
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         PrintWriter out = new PrintWriter(s1.getOutputStream(),true);
         System.out.print("Client:");
         String request = br.readLine();
         while(!(request.contentEquals("bye"))){
            out.println(request);
            String reply = is.readLine();
            System.out.println("Server:" + reply);
            System.out.print("Client:");
            request = br.readLine();
         }
         out.close();                   
         is.close();
         s1.close();
   }
}

Output on Client Screen:

Client:hello
Server:hello client
Client:how are you?
Server:I am fine...what about you?
Client:bye

No comments:

Post a Comment