ServerSocket to be used with multi clients we attach separate thread for each client to to work probably,but the problem is the connection works fine and accept all clients but only serve last connection. So is't a problem or this is normal.

Server Code:

   ServerSocket serverSocket=null;
    Socket client;
        System.out.println("Establishing Connection. Please wait...");
   try{

           serverSocket =new ServerSocket(58342);            
           System.out.println("Serever Started.");
       }catch(Exception e)
       {
           System.out.println(e.getMessage());
       }

        while (true) {
                try{
             client = serverSocket.accept();
                     new ClientThread(client).start();
                }catch(Exception e)
                {
                    String err=e.getMessage();
                    if(err == null)
                    {
                       break;
                    }else{
                        System.out.println(e.getMessage());
                    }
                }

        }

ClientThread

public class ClientThread extends Thread{

    private static Socket client;
    private static String line="";
    private static DataInputStream input = null;
    private static DataOutputStream output = null;

    public ClientThread(Socket serv)
    {
      try {
            client =serv;
            input=new DataInputStream(client.getInputStream());
            output=new DataOutputStream(client.getOutputStream());
            System.out.println("New Client Connected to port:"+
                    client.getPort());
            } catch (Exception e) {
                    System.out.println(e.getMessage());
            }       
    }
}
有帮助吗?

解决方案

All of your variables in your ClientThread are static!!

This means that they are shared across all instances of ClientThread. So they are overwritten each time you create a new ClientThread.

Remove the static and you should be fine.

Looks to me like you might need to read some documentation.

其他提示

You must be doing I/O in the constructor of ClientThread.

Don't.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top