java socket 被阻塞了,如何避免使用Java ServerSocket进行阻塞?

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 performed on the data and are just different because they arrive n different ports. I went ahead and coded an implementation using Java's ServerSocket class, only to realize later that the accept() method of the ServerSocket class is block and my implementation cant afford that. So now i was thinking of implementing the same using Java NIO but after having gone through some tutorials i think i am more confused than how i started. It would be great if someone here could walk me through the whole process, even of it be in pseudo code or jus technical "what to do next"'s.

This is what i plan to achieve.

Listen, like for ever on 2 ports by calling 2 similar threads.(non blocking)

A remote device from some network location connects, sends data and then disconnects.

I think if only knowledge of how NIO can be used to set up a server to listen on a port say port 80, on localhost,is achieved, the rest is all pretty easy to implement.

Cheers

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值