Multithreading with client server program

前端 未结 2 1864
情书的邮戳
情书的邮戳 2021-01-07 12:29

I am trying to implement multi threading with a client/server program I have been working on. I need to allow multiple clients to connect to the server at the same time. I

相关标签:
2条回答
  • 2021-01-07 13:18

    Your server code should address implement below functionalities.

    1. Keep accepting socket from ServerSocket in a while loop

    2. Create new thread after accept() call by passing client socket i.e Socket

    3. Do IO processing in client socket thread e.g ClientWorker in your case.

    Have a look at this article

    Your code should be

    ServerSocket serverSocket = new ServerSocket(portNumber);
    while(true){
      try{
        Socket clientSocket = serverSocket.accept();
        Thread thread = new ClientWorker(clientSocket);
        thread.start(); //start thread
      }catch(Exception err){
         err.printStackTrace();
      }
    }
    
    0 讨论(0)
  • 2021-01-07 13:34

    How many times does serverSocket.accept() get called? Once. That's how many clients it will handle. Subsequent clients trying to contact will not have anybody listening to receive them.

    To handle more clients, you need to call serverSocket.accept() in a loop.

    0 讨论(0)
提交回复
热议问题