Search code examples
javamessagejava-threads

Java simple server client


I am making a simple threaded server client messaging application in java. My problem is that when the client is open the server gets the message but echoes the message back to only the client that sent the message and not the other client. How do I get it to send to all the clients that are connected to the server.

Server Code

import java.io.*;
import java.net.*;
public class ThreadedSever
{
  private static final int port=5000;
  //Threaded Server
  public ThreadedSever(){
     System.out.println("A multi-threaded server has started...");
     ServerSocket serverSocket = null; 
     try {
         serverSocket = new ServerSocket(port);
     }catch(Exception e){
         System.out.println("Could not create a server socket: " + e);
     }
     //Chat with the client until breaks connection or says bye
     try{
         while(true){
             System.out.println("Waiting for client communication");
             Socket currentSocket = serverSocket.accept();
             //Create a new thread to deal with this connection
             new ServerThread(currentSocket);
         }

     }catch(Exception e){
         System.out.println("Fatal Server Error!");
     }
  }
   //Inner class to handle individual commincation
   private class ServerThread extends Thread{
   private Socket sock;
   private DataInputStream in = null;
   private DataOutputStream out = null;

   public ServerThread(Socket sock){
       try{
           this.sock = sock;
           in = new DataInputStream(this.sock.getInputStream());
           out = new DataOutputStream(this.sock.getOutputStream());
           System.out.print("New client connection established");
           out.writeUTF("Type bye to exit, otherwise, prepare to be echoed");
           start();
       }catch(Exception e){
           System.out.println("Oops");
       }
   }
   public void run(){
     try{
        String what = new String("");
        while(!what.toLowerCase().equals("bye")){
            what = in.readUTF();
            System.out.println("Client told me: " + what);
            out.writeUTF(what);
        }
     }catch(Exception e){
         System.out.println("Connection to current client has been broken");
     }
     finally{
       try{
           sock.close();
       }catch(Exception e){
           System.out.println("Error socket could not be closed");
       }
     }
   }
  }
  public static void main(){
    new ThreadedSever();
  }
}

Client Code

import java.io.*;
import java.net.*;
public class simpleClient
{
    private static final int port= 5000;
    private static String server = "localhost";
    private static Socket socket = null;
    private static DataInputStream input = null;
    private static DataOutputStream output = null;
    private static InputStreamReader inReader = null;
    private static BufferedReader stdin = null;

    public static void main(){
        try{
            socket = new Socket(server, port);
        }catch(UnknownHostException e){
            System.err.println("Unknow IP address for server");
            System.exit(-1);
        }
        catch(IOException e){
            System.err.println("No server found at specified port");
            System.exit(-1);
        }
        catch(Exception e){
            System.err.println("Something happened!");
            System.exit(-1);
        }
        try{
            input = new DataInputStream(socket.getInputStream());
            output = new DataOutputStream(socket.getOutputStream());
            inReader = new InputStreamReader(System.in);
            stdin = new BufferedReader(inReader);
            String what = new String("");
            String response;
            while(!what.toLowerCase().equals("bye")){
                // Expect something from the server and output it when it arrives
                response = input.readUTF();
                System.out.println("Server said  \"" + response + "\"");
                //Read a line from the user and send it to the server
                what = stdin.readLine();
                output.writeUTF(what);
            }
        }
        catch(IOException e){
            System.err.println("Broken connection with server");
            System.exit(-1);
        }

    }
}

Solution

  • You can define a method echoMessage in each ServerThread. Every time when a ServerThread is instantiated, add that instance to a list in ThreadedSever. And also make ServerThread an observer when ever ServerThread receives data, then the observer method should call echoMessage on each element in the ServerThread list.