Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ServerSocket只接受2个连接_Java_Sockets - Fatal编程技术网

Java ServerSocket只接受2个连接

Java ServerSocket只接受2个连接,java,sockets,Java,Sockets,现在,我对客户机-服务器应用程序有点傲慢,例如,通过java应用程序与运行服务器应用程序的raspberry pi进行通信 通过这个,我发现了一个问题,我没有找到一个可能的解决办法。使用以下代码,我可以连接到服务器两次,但在2次连接后,它将不接受任何更多的连接。例如,我第一次启动客户机,它可以很好地工作。然后我关闭客户端并再次启动它,它就会再次工作。但如果我关闭它,第三次启动它,它将一事无成。服务器将不接受该连接。我在我的私人网络中尝试了不同的PC,但没有第三次连接 以下是我在服务器上运行的代码

现在,我对客户机-服务器应用程序有点傲慢,例如,通过java应用程序与运行服务器应用程序的raspberry pi进行通信

通过这个,我发现了一个问题,我没有找到一个可能的解决办法。使用以下代码,我可以连接到服务器两次,但在2次连接后,它将不接受任何更多的连接。例如,我第一次启动客户机,它可以很好地工作。然后我关闭客户端并再次启动它,它就会再次工作。但如果我关闭它,第三次启动它,它将一事无成。服务器将不接受该连接。我在我的私人网络中尝试了不同的PC,但没有第三次连接

以下是我在服务器上运行的代码:

public class Receiver {

private final Logger logger = Logger.getLogger(this.getClass().getName());

private ServerSocket serverSocket;
private boolean isRunning;

public Receiver(int port) {
    isRunning = true;
    try {
        serverSocket = new ServerSocket(port);
        logger.log(Level.FINER, "start listening at port " + port);
        logger.log(Level.FINER, "established successful.");
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Error while opening socket:\n" + LogUtil.getStackTrace(e));
        System.exit(1);
    }
}

/**
 * server starts to listen at the specific port
 */
public void listenServer() {
    logger.log(Level.FINER, "Server is listening");

    while (isRunning) {
        try {
            final Socket clientsocket = serverSocket.accept();
            logger.log(Level.FINER, "Server accepted Connection from " + clientsocket.getInetAddress());
            new Thread(new Runnable() {

                @Override
                public void run() {
                    handleConnection(clientsocket);
                }
            }).start();
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Connection with Client failed.");
        }
    }
}

/**
 * handles the given connection
 * 
 * @param clientSocket
 *            the given client socket for this connection
 */
private void handleConnection(Socket clientSocket) {

    ObjectInputStream instream = null;
    ObjectOutputStream outstream = null;

    try {
        outstream = new ObjectOutputStream(clientSocket.getOutputStream());
        instream = new ObjectInputStream(clientSocket.getInputStream());
        final RequestProcessor processor = new RequestProcessor();
        final InetAddress inetAdress = clientSocket.getInetAddress();

        logger.log(Level.FINER, "handle connection from " + inetAdress);

        Object inob;
        while ((inob = instream.readObject()) != null) {
            logger.log(Level.FINER, "received Object from " + inetAdress);
            final ObjectOutputStream finalOutputStream = outstream;
            final Object finalInob = inob;

            new Thread() {
                public void run() {
                    setPriority(MAX_PRIORITY);
                    Object outob;
                    try {
                        outob = processor.processObject(finalInob);
                        logger.log(Level.FINER, "send Respond to: " + inetAdress + " Error: " + (outob instanceof ErrorMessage));
                        finalOutputStream.writeObject(outob);
                        finalOutputStream.flush();
                    } catch (IOException e) {
                        logger.log(Level.SEVERE, "Connection closed to " + inetAdress);
                    }
                }
            }.start();
        }

        closeConnection(clientSocket, instream, outstream);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Connection closed to " + clientSocket.getInetAddress());
    } catch (ClassNotFoundException e) {
        logger.log(Level.SEVERE, "Connection closed to " + clientSocket.getInetAddress());
    } finally {
        closeConnection(clientSocket, instream, outstream);
    }

}

/**
 * closes InputStream, OutputStream and socket
 * 
 * @param socket
 * @param instream
 * @param outstream
 */
private void closeConnection(Socket socket, InputStream instream, OutputStream outstream) {
    this.isRunning = false;
    if (instream != null) {
        try {
            instream.close();
        } catch (IOException e) {
        }
    }
    if (outstream != null) {
        try {
            outstream.close();
        } catch (IOException e) {
        }
    }
    if (socket != null) {
        try {
            socket.close();
        } catch (IOException e) {
        }
    }
    logger.log(Level.FINER, "Connection was closed to client " + socket.getInetAddress());
}

/**
 * closes all connections and ends the server
 */
public void endAllConnections() {
    this.isRunning = false;

    if (this.serverSocket != null)
        try {
            this.serverSocket.close();
        } catch (IOException e) {
            // do nothing
        }
      }
  }
下面是我用来连接到此服务器的客户端代码:

public class SocketConnector implements IConnector {

    private final Logger logger = Logger.getLogger(this.getClass().getName());

    private Socket s;
    private ObjectOutputStream oos;
    private ObjectInputStream ois;

    /**
     * creates a new connection
     * 
     * @param host
     *            given host
     * @param port
     *            given port
     * 
     * @throws UnknownHostException
     * @throws IOException
     */
    public SocketConnector(String host, int port) throws UnknownHostException, IOException {
        logger.log(Level.FINER, "Establish connection to " + host + ":" + port);
        s = new Socket(host, port);
        oos = new ObjectOutputStream(s.getOutputStream());
        ois = new ObjectInputStream(s.getInputStream());
    }

        // some methos which use oos and ois.
有人知道为什么当两个客户端连接并断开连接时,服务器不接受更多的连接吗?我在谷歌上搜索了很多地方,但没有找到合适的答案:/ 服务器日志显示它甚至不接受新连接

提前感谢:)

情况是:

调用
final Socket时clientsocket=serverSocket.accept()第一次,它正在等待第一个客户端。当第一个客户端连接时,将此客户端传递给一个线程,然后继续调用
final Socket clientsocket=serverSocket.accept()的循环第二次。由于启动一个线程比执行下一个循环需要更多的时间,
isRunning
仍然是
true
。在
handleConnection(Socket-clientSocket)
中,调用
closeConnection(clientSocket、流内、流外)
isRunning
设置为
false
。这就是重点。当第二个客户端连接时,您还将此客户端传递给另一个线程,然后继续循环,其中
isRunning
false
,因此循环终止。因此,您无法访问第三个客户端。

您是否在Windows中运行?因为我认为TCP/IP堆栈限制为每个主机2个连接,您可以通过修改Windows注册表(或使用IP地址和主机名等备用主机名)来进行调整,所以此代码还存在其他问题。1.对象流应该在run()方法中创建,而不是在构造函数中创建:否则它们在accept()线程中执行,可能会阻塞它。2.ObjectInputStream不会返回null,除非您编写了null,所以在它不返回null的情况下进行循环是没有意义的。它在流的末尾抛出EOFEException:捕捉到它,当你们得到它时就打断它@JasonSperske有一个TCP待办事项限制,但它远远高于2。谢谢。Vutran解决了主要问题。我会再看一次,按照你的建议让它更干净(EJP:)还有一个问题。为每个传入连接启动的Runnable应该与服务器类无关,并且不应该调用其中的方法。这确实是基本问题。谢谢:)这就是问题所在。真遗憾,我没看到:/真的没看到,我把它设为false^^