gpt4 book ai didi

java - 无法关闭服务器套接字

转载 作者:可可西里 更新时间:2023-11-01 02:49:41 25 4
gpt4 key购买 nike

我正在制作一个简单的聊天服务器,只是为了让每个连接都在一个新线程上运行。

旧版本为服务器启动了一个线程,它做了一个 while 循环,当发送停止消息时会停止,然后关闭套接字。

新版本永远循环并为每个新连接创建一个新线程。现在我无法关闭套接字连接。

如果您按下一个键并且主线程停止,套接字将保持打开状态。因此,当我再次运行程序时,我需要更改套接字号。

服务器代码

while(true)
{
///////////////////////////////////////////////////
// get a new connection
///////////////////////////////////////////////////
System.out.println("Aceepting connections on port 1030 \r");

try{
// Get New Connection

// wait for ever on accepting new connections
server.setSoTimeout(0);
connection=server.accept();

cConnection thread = new cConnection("thread3", connection);
} catch(IOException ec)
{
System.out.println(ec.getMessage());
}
}

启动服务器的代码

现在每条消息都进入一个新线程,所以我无法告诉它停止并关闭套接字。

最佳答案

您需要提供一个必须全局可访问的标志,以便当某些客户端想要停止服务器时,然后更改变量 ans 停止 bucle。例如:

class YourServer {
private static boolean execute = true;

public static synchronized void stop() {
execute = false;
}
public void yourMethod() {
while(execute) {
// implement your server here
}
}
}

当客户端发送命令停止时,你必须做

  YourServer.stop();

关于java - 无法关闭服务器套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8317407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com