如何编写一个接受多个客户端套接字的ServerSocket?

How to write A ServerSocket which accept multiple clicent Socket?

我正在从事套接字编程。我已经构建了一个应该接受多个客户端的服务器。在这里我有特定数量的客户端,客户端每 10 秒向服务器发送一次消息,服务器必须处理 it.The 我遇到的问题是我无法连接多个服务器,这里单个客户端是连续的 运行ning programm in while(true) 因此,如果一个客户端发送请求,另一个客户端将无法连接。这是我的程序。

服务器

public class SimpleServer extends Thread {

private ServerSocket serverSocket = null;
private Socket s1 = null;

SimpleServer() {
    try {
        serverSocket = new ServerSocket(1231);
        this.start();
    } catch (IOException ex) {
        System.out.println("Exception on new ServerSocket: " + ex);
    }
}

public void run() {
    while (true) {
        try {

            System.out.println("Waiting for connect to client");
            s1 = serverSocket.accept();
            System.out.println("Connection received from " + s1.getInetAddress().getHostName());

            InputStream s1In = s1.getInputStream();
            DataInputStream dis = new DataInputStream(s1In);

            String st = dis.readUTF();
            System.out.println(st);
            s1In.close();
            dis.close();
            s1.close();
           // throw new ArithmeticException();

        } catch (IOException ex) {
            Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
        }
         catch (Exception e) {
             System.out.println("Exceptiopn: "+e);
        }

    }
}

public static void main(String args[]) throws IOException {

    new SimpleServer();
 }
}

服务器工作正常,但我无法编写应该 运行 在 while(true) 循环中向服务器发送消息并允许其他客户端也连接到服务器的客户端程序。 但是对于一个客户,我是这样写的,

public class SimClient extends Thread {

private Socket s1 = null;

SimClient() {
    //this.start();

}

public void run() {
    int i=0;
    try {
        s1 = new Socket("localhost", 1231);
    } catch (IOException ex) {
        Logger.getLogger(SimClient.class.getName()).log(Level.SEVERE, null, ex);
    }
   // while (i<10) {
        try {
            // Open your connection to a server, at port dfg1231


            OutputStream s1out = s1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(s1out);

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             System.out.println("Enter Data from Client:");
            String s = br.readLine();
            dos.writeUTF(s);
            dos.flush();
            s1out.close();
            dos.close();
           // s1.close();
            i++;

        } catch (IOException ex) {

           //ex.printStackTrace();
            System.out.println("Exception in While: "+ex.getMessage());
        }


    //}
}

public static void main(String args[]) throws IOException {

   SimClient s= new SimClient();
   s.start();
}


 }

所以谁能帮我写个客户端程序。对我帮助很大。

就像您有一个用于 ServerSocket 的线程一样,您需要为 serverSocket.accept() 返回的每个套接字创建一个线程,然后它立即循环返回以阻塞并等待接受另一个套接字。创建一个名为 SocketHander 的 class,它扩展 Thread 并在构造函数中接受一个 Socket。

public class SocketHandler extends Thread {
    private Socket socket;

    public SocketHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        // use the socket here
    }
}

然后回到 ServerSocket 处理程序...

for (;;) {
    SocketHandler socketHander = new SocketHandler(serverSocket.accept());
    socketHander.start();
}

通常使用固定大小的线程池是个好主意,因为如果请求很高,以临时方式创建线程可能会导致服务器 运行 线程不足。

public class SimpleServer extends Thread {

private ServerSocket serverSocket = null;
private static ExecutorService executor = Executors.newFixedThreadPool(100);

SimpleServer() {
    try {
        serverSocket = new ServerSocket(1231);
        this.start();
    } catch (IOException ex) {
        System.out.println("Exception on new ServerSocket: " + ex);
    }
}

public void run() {
while (true) {
    try {

        System.out.println("Waiting for connect to client");
        final Socket s1 = serverSocket.accept();
        executor.execute(new Runnable() {

            public void run() { 
                try {
                    System.out.println("Connection received from " + s1.getInetAddress().getHostName());

                    InputStream s1In = s1.getInputStream();
                    DataInputStream dis = new DataInputStream(s1In);

                    String st = dis.readUTF();
                    System.out.println(st);
                    s1In.close();
                    dis.close();
                    s1.close();
                } catch(Exception e) {
                    System.out.println("Exceptiopn: "+e);
                }
                // throw new ArithmeticException();
            }});

         } catch (IOException ex) {
                     Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
         } catch (Exception e) {
              System.out.println("Exceptiopn: "+e);
         }

}
}

public static void main(String args[]) throws IOException {

    new SimpleServer();
}
}