如何重新打开Java套接字

0 java sockets

我正在循环中读取Java Socket.

如果读取抛出异常,我想重新打开套接字.

为了测试它,我只需关闭套接字并捕获异常.

当我尝试重新打开套接字时,问题是:

serverSocket = new ServerSocket(port)
socket = serverSocket.accept()
Run Code Online (Sandbox Code Playgroud)

它引发了一个异常:

java.net.BindException: The socket name is already in use
Run Code Online (Sandbox Code Playgroud)

这是测试的直接问题.但它也可能在生产中发生.

如何通过在抛出异常后打开新的套接字连接来可靠地恢复?

小智 5

如果我误解了你在说什么,我很抱歉.

如果套接字上的read()方法失败,则不会关闭ServerSocket.

您仍然可以在不创建新服务器的情况下调用serverSocket.accept().我认为这就是你获得BindException的原因.


Dav*_*itz 5

您需要的是创建 ServerSocket 一次,并将任何接受的套接字传递给其处理程序 - 通常在不同的线程中完成。

你得到的错误是因为你试图在同一个端口上侦听两次,这是不可能的。

这篇文章或许能帮到你。这是代码示例之一:

public void await() {
    ServerSocket serverSocket = null;
    int port = 8080;
    try {
        serverSocket =  new ServerSocket(port, 1,
        InetAddress.getByName("127.0.0.1"));
    }
    catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // Loop waiting for a request
    while (!shutdown) {
        Socket socket = null;
        InputStream input = null;
        OutputStream output = null;
        try {
            socket = serverSocket.accept();
            input = socket.getInputStream();
            output = socket.getOutputStream();

            // create Request object and parse
            Request request = new Request(input);
            request.parse();

            // create Response object
            Response response = new Response(output);
            response.setRequest(request);
            response.sendStaticResource();

            // Close the socket
            socket.close();

            //check if the previous URI is a shutdown command
            shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
        }
        catch (Exception e) {
            e.printStackTrace();
            continue;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)