How can I use multi-threading to allow multiple clients on to a server? [duplicate]

心不动则不痛 提交于 2019-12-11 09:54:39

问题


I have two java classes, one for a server and one for a client. The connection is established between both of them using a regular socket. How can I allow many instances of the client class to connect to the server simultaneously using multi-threading? I tried searching on SO but I couldn't really find any concise/clear answers.

Here are my important methods (both of them are in the Server class):

public void startRunning() {

    try {
        server = new ServerSocket(portNum, 10); // port num and backlog

        while (true) {
            try {

                waitForConnection();
                setupStreams();  //sets up streams
                whileChatting(); //exchanges messages
            } catch (EOFException e1) {
                showMessage("\n Server ended the connection");

            } finally {
                closeEverything();  //closes all streams
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void waitForConnection() throws IOException {

    showMessage(" Waiting for connections...\n");
    connection = server.accept();
    showMessage(" Connected to "
            + connection.getInetAddress().getHostName());

}

回答1:


Here is a simple example. A new Thread replies to every new incoming Client.

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

class Server implements Runnable {
  public static final int port = 5678;


  public void run() {
    try{
       ServerSocket server = new ServerSocket(port);

       while (true) 
       {
           final Socket client = server.accept();
           new Thread() {
                public void run() {
                      try{
                          ObjectInputStream in = 
                          new ObjectInputStream( client.getInputStream() );
                         String msg = (String) in.readObject();
                         System.out.println(msg);
                        }
                      catch(Exception e){System.err.println(e);}

          }}.start();
       }
      }
    catch(IOException e){System.err.println(e);}
    }

}

class Client {

  public void writeMessage(String msg) throws IOException {
     new ObjectOutputStream((new Socket("localhost",Server.port).getOutputStream())).writeObject(msg);
  }
}

public class ClientServer{
  public static void main(String[] args) throws IOException{
    Server server = new Server("My Multithreaded Server");
    new Thread(server).start();
    Client client1 = new Client();
    Client client2 = new Client();
    client1.writeMessage("Hello !");
    client2.writeMessage("Give me five !");
  }
}


来源:https://stackoverflow.com/questions/33584373/how-can-i-use-multi-threading-to-allow-multiple-clients-on-to-a-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!