ServerSocket进行阻塞

ServerSocket进行阻塞

本文介绍了如何避免使用Java ServerSocket进行阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作在一个套接字侦听器,必须监听2端口的2种类型的数据(端口80和端口81)。这些数据与对数据执行的操作类型非常相似,并且仅因为它们到达n个不同端口而不同。我继续编写一个实现使用Java的ServerSocket类,只是实现后来的ServerSocket类的accept()方法是块和我的实现不能承受。所以现在我正在考虑使用Java NIO实现相同的,但经过一些教程后,我想我比我开始更困惑。这将是巨大的,如果有人在这里可以带我通过整个过程,即使是在伪代码或jus技术下一步做什么。
这是我计划实现的。

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.

通过调用2个类似的线程来监听2个端口。远程设备从某个网络位置连接,发送数据然后断开连接。

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.

我想如果只知道如何使用NIO来设置服务器监听端口

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.

干杯

推荐答案

当你需要扩展到数千个并发连接时,需要调用NIO。

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

否则,建议使用多线程。对于每个端口(及其对应的 ServerSocket ),创建一个在循环中调用 accept()的线程。

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.

当一个新的 Socket 被接受,创建专用于该连接的另一个线程。它取决于应用程序,但通常这个线程将从套接字读取(阻塞操作),并执行请求的操作,将结果写回套接字。

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.

这种架构将扩展到大多数桌面平台上的数百个连接。并且编程模型是相当简单的,只要每个连接是自包含和独立的其他(这避免了并发问题)。介绍NIO将提供更多的可扩展性,但需要很多复杂性。

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.

这篇关于如何避免使用Java ServerSocket进行阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:06