简体   繁体   English

如何使用java.net.ServerSocket连续监听端口

[英]How to continuously listen on port with java.net.ServerSocket

I have a java.net.ServerSocket that is am using to listen for connections. 我有一个java.net.ServerSocket ,用于监听连接。 I am using it's accept() method in order to obtain connections from clients and then handle them appropriately. 我正在使用它的accept()方法以便从客户端获取连接,然后适当地处理它们。 I wish to continously be listening for clients and never be unavailable to them. 我希望不断地倾听客户的意见,并且永远不会对他们不可用。 Currently I have code similar to this: 目前,我有与此类似的代码:

ServerSocket serverSocket = ...
while (shouldBeListening) {
    handleClient(serverSocket.accept());
}

The handleClient method may take a small amount of time (less than a tenth of a millisecond). handleClient方法可能会花费少量时间(不到十分之一毫秒)。 I am worried that between the time the ServerSocket.accept() method returns and it is called again that a request for a connection could have been missed. 我担心在ServerSocket.accept()方法返回与再次调用之间可能会错过连接请求。 What is the best way to solve this issue? 解决此问题的最佳方法是什么?

EDIT: The way I am implementing it currently creates a new thread in the handleClient method, but even this takes time (especially since this is being run on a Raspberry Pi ), I am worried that if a connection is requested while the handleClient method is being executed then it may be rejected because accept() is not being run. 编辑:我实现它的方式当前在handleClient方法中创建一个新的线程,但即使这需要时间(特别是因为它正在Raspberry Pi上运行),我担心如果在handleClient方法被请求时进行连接被执行,则可能会被拒绝,因为没有运行accept()

Something like this. 这样的事情。

 ServerSocket listener = new ServerSocket(8001);
    try {
      while (true) {
         Socket socket = listener.accept();

Then you can pass socket reference to the handler class you have. 然后,您可以将套接字引用传递给您拥有的处理程序类。 Make that class implements Runnable . 使该类实现Runnable Create a new thread each time you pass the socket reference to the handler class to handle the requests simultaneously. 每次将套接字引用传递给处理程序类以同时处理请求时,请创建一个新线程。 Please see the below links for solutions. 请查看以下链接以获取解决方案。 If you need a full code. 如果您需要完整的代码。 Let me know. 让我知道。

Runnable Sample by Jenkov Jenkov的Runnable Sample

ThreadPool Sample - Stackoverflow ThreadPool示例-Stackoverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM