JAVA初级问题—关于TCP(Server与Client端都是循环的,但是程序只能执行一次,第二次就卡住)

2025-02-25 04:05:26
推荐回答(1个)
回答1:

try {
ss = new ServerSocket(3001);

this.ranMethod();// 生成5个随机数
System.out.println();
} catch (IOException e) {
System.out.println("端口被占用!请重启服务器!");
e.printStackTrace();
}
while (over!=true) {
这里每次监听一个客户端。。。

try {System.out.println("监听客户端");
client = ss.accept();// 监听客户端

} catch (IOException e) {

System.out.println("监测客户端连接异常。");
e.printStackTrace();
}
第二个循环后,已经是新的客户端了。
str = this.accpetMethod();// 输出客户端信息
System.out.println(str);
bool = this.message(str);// 判断客户端输入是否为数字,是返回true,否返回false.
if (bool == true) {
bool = this.judgement(bool, str);
this.sendMethod(bool);
} else {
try {
dos = new DataOutputStream(client.getOutputStream());
dos.writeUTF("输入错误,请输入0~100间的数字!");
dos.flush();
//
} catch (IOException e) {
e.printStackTrace();
}
}
}

主要的问题是,你每一次循环都会执行accept,等待新的客户端连接。
要改的话,首先要把Accecpt后的client的处理放在独立的循环里面。也就是:

while (! over)
{
accept ()

while (client answer is wrong) // loop for current cilent.
{
// read client input.
// check client answer
// write message to client.

}
}

这样,服务器会在每次接受到一个客户端后,会进行持续的处理,直到客户端退出,然后返回accecpt下一个。

你能发现问题在于服务器同时只能为一个client服务,所以,很简单的把第二个while改成在单独的线呈里执行就好了