Welcome to the World of Programming

Welcome to the World of Programming

Search this blog

Client-to-Server Chat Program

In this Program Only the Client Communicates with the Server and Server receives Client's Messages but send's any messages to client.


Server Side Code:

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

class Serv{
    public  static  void  main(String   args[]) throws  Exception {
        ServerSocket  ss = new ServerSocket(12345);
        Socket  s= ss.accept();
        System.out.println("connected  to client");
        BufferedReader  br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String str=br.readLine();
        while( ! str.equals("exit")){
            System.out.println("from client " + str);
            str=br.readLine();
        }
        br.close();
    }
}

Client Side Code:

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

class  Clien{
    public static void main(String args[])  throws Exception {
        Socket  c= new Socket("localhost", 12345);
        System.out.println("Client is ready");
        BufferedReader kb= new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw= new PrintWriter(c.getOutputStream(), true);
        String str="";
        while(!(str= kb.readLine()).equals("exit")) {
            pw.println(str);
        }
        pw.println("exit");
        pw.close();
        kb.close();
    }
}


No comments:

Post a Comment