在单独的线程中创建ServerSocket? [英] Creating the ServerSocket in a separate thread?

查看:95
本文介绍了在单独的线程中创建ServerSocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用 ServerSocket 时遇到问题。

I have a problem with using a ServerSocket in my application.

我正在创建 ServerSocket 在我的应用程序的构造函数中。套接字的构造函数调用 accept()方法等待客户端连接。

I'm creating the ServerSocket in the constructor of my application. The constructor of the socket calls the accept() method to wait for a client to connect.

问题是 accept()方法冻结我的整个应用程序,直到客户端连接。所以我想问一下,如果在另一个线程中创建整个 ServerSocket ,还有 ServerSocket 在我的主应用程序旁边调用 accept()方法?

The problem is that the accept() method is freezing my whole application until a client connects. So I would like to ask if there's an alternative to creating the whole ServerSocket in a separate thread, that the constructor of the ServerSocket and its accept() method is called beside my main application?

编辑:

感谢Olivier的建议,将.accept放入runnable并创建一个线程池来处理客户端连接。

Thanks to Olivier for the advice, putting the .accept into a runnable and creating a threadpool to handle the clientconnections.

多数民众赞成我的代码:

Thats my code right now:

  public void start(){

      final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);

      Runnable serverTask = new Runnable() {
          @Override
          public void run() {

              try {
                  serverSocket = new ServerSocket(port);

                  while (true) {
                      Socket clientSocket = serverSocket.accept();
                      objectout = new ObjectOutputStream(clientSocket.getOutputStream());
                      clientProcessingPool.submit(new ClientTask(clientSocket,objectout)); 
                  }
              } catch (IOException e) {
                  System.err.println("Accept failed.");
              }

          }
      };

万事如意!谢谢!

推荐答案

通常,我使用N + 1个线程:一个用于ServerSocket,以避免阻塞整个应用程序等待供客户连接;和N个线程来处理客户端的请求,N是线程池的大小(我建议使用线程池而不是为每个客户端创建一个新线程)。

Usually, I use N+1 threads for this : one for the ServerSocket, to avoid blocking the whole application waiting for a client to connect; and N threads to process the client's requests, N being the size of the thread pool (I recommend using a thread pool over creating a new thread per client).

这是一个例子(只是编码它,你可能希望有更好的异常管理等,但这是一个最小的工作示例)

Here is an example (just coded it, you may want to have better exception management and such, but this is a minimal working example)

public class Server {

    public static void main(String[] args) {
        new Server().startServer();
    }

    public void startServer() {
        final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);

        Runnable serverTask = new Runnable() {
            @Override
            public void run() {
                try {
                    ServerSocket serverSocket = new ServerSocket(8000);
                    System.out.println("Waiting for clients to connect...");
                    while (true) {
                        Socket clientSocket = serverSocket.accept();
                        clientProcessingPool.submit(new ClientTask(clientSocket));
                    }
                } catch (IOException e) {
                    System.err.println("Unable to process client request");
                    e.printStackTrace();
                }
            }
        };
        Thread serverThread = new Thread(serverTask);
        serverThread.start();

    }

    private class ClientTask implements Runnable {
        private final Socket clientSocket;

        private ClientTask(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            System.out.println("Got a client !");

            // Do whatever required to process the client's request

            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

这篇关于在单独的线程中创建ServerSocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆