首页 文章

客户端关闭后保持套接字服务器打开

提问于
浏览
0

我已经实现了一个带有服务器和单个客户端的套接字 . 它当前的结构方式,只要客户端关闭,服务器就会关闭 . 我的意图是让服务器运行直到手动关闭 .

这是服务器:

public static void main(String args []){;

try
    {
         ServerSocket socket= new ServerSocket(17);

         System.out.println("connect...");
         Socket s = socket.accept();
        System.out.println("Client Connected.");


        while (true)
            {

                work with server

            }

}
catch (IOException e)
    {
        e.getStackTrace();
     }

}

我已经尝试用另一个 while(true) 循环包围整个try / catch循环,但它什么也没做,同样的问题仍然存在 . 有关如何保持服务器运行的任何想法?

2 回答

  • 0

    它看起来像's going to happen in your code there is that you connect to a client, infinitely loop over interactions with the client, then when someone disrupts the connections (closes clearning, or interrupts it rudly - e.g., unplug the network cable) you'将要获得一个 IOException ,将你发送到catch子句运行然后继续(我猜"after that"是你的main()的结束?)...

    所以你需要做的是,从那时起,循环回到accept()调用,这样你就可以接受另一个新的客户端连接 . 例如,这里有一些伪代码:

    create server socket
    while (1) {
        try {
            accept client connection
            set up your I/O streams
    
            while (1) {
                interact with client until connection closes
            }
        } catch (...) {
            handle errors
        }
    } // loop back to the accept call here
    

    另外,请注意这种情况下try-catch块的位置,以便在accept-loop中捕获和处理错误 . 这样,单个客户端连接上的错误将发送回accept()而不是终止服务器 .

  • 5

    将单个服务器套接字保留在循环之外 - 循环需要在accept()之前启动 . 只需将ServerSocket创建放入单独的try / catch块即可 . 否则,您将打开一个尝试在同一端口上侦听的新套接字,但只关闭了一个连接,而不是serverSocket . 服务器套接字可以接受多个客户端连接 .

    当它工作时,您可能希望在accept()上启动一个新的Thread以支持多个客户端 . 最简单的方法是添加一个实现Runnable接口的“ClinentHandler”类 . 在客户端中,您可能希望将套接字的读取放入单独的线程中 .

    这是家庭作业/某种作业吗?

相关问题