How can I avoid blocking with Java ServerSocket?

前端 未结 3 2164
长发绾君心
长发绾君心 2021-02-19 15:56

Im working on a socket listener that has to listen on 2 ports for 2 types of data( port 80 and port 81). These data are very similar as in the kind of operations that are perfor

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 16:23

    NIO is called for when you need to scale to many thousands of simultaneous connections.

    Otherwise, I'd suggest using multiple threads. For each port (and its corresponding ServerSocket), create a thread that calls accept() in a loop. These calls will block, but that is alright because other threads are running, taking care of any available tasks.

    When a new Socket is accepted, create another thread that is dedicated to that connection. It depends on the application, but typically this thread will read from the socket (a blocking operation), and perform the requested operation, writing the results back to the socket.

    This architecture will scale to many hundreds of connections on most desktop platforms. And the programming model is fairly simple, as long as each connection is self-contained and independent of the others (this avoids concurrency issues). Introducing NIO will provide more scalability, but requires a lot of complexity.

提交回复
热议问题