gpt4 book ai didi

Java 与服务器的有限连接

转载 作者:行者123 更新时间:2023-12-01 11:57:10 25 4
gpt4 key购买 nike

我是java新手,尤其是java网络新手,但我想做的是设置一个服务器(用于游戏)。当两个客户端连接到服务器时,我想拒绝任何其他连接。我可以关闭 ServerSocket 吗?如果 ServerSocked 关闭,那两个作为线程运行并存储在集合中的连接仍然存在并且能够与服务器通信?我希望你明白我的意思。

这是源代码:

//Server
public synchronized List<ClientThread> getClients(){
return clients;
}


public void run() {
try {
while(true){

Socket clsock = srvsock.accept();

if(getClients().size() == 2){
System.out.println("Too many connections!");
clsock.close();
continue;
}

ClientThread clt = new ClientThread(clsock);
clients.add(clt);
clt.start();
System.out.println("Connection accepted.");

}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
}

使用这段代码,我无法在客户端上检测连接是否仍然存在,或者服务器是否已关闭连接。提前致谢。

最佳答案

测试客户端代码:

Socket s = new Socket("localhost", 8932);               
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

for (int i=0; i<20; i++) {
bw.write(String.valueOf(i));
bw.newLine();
bw.flush();
Thread.sleep(1000);
}
bw.close();

对于 ClientThread:

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while (true) {
String misc = in.readLine();
System.out.println(misc);
if (misc==null || misc.length()==0)
break;
}
in.close();

输出:

Connection accepted.
0
Connection accepted.
0
1
Too many connections!
1
2
2
3

所以它按照你的预期工作。顺便说一句,实现 Runnable 通常比扩展 Thread 更好 - 请参阅 "implements Runnable" vs. "extends Thread"

关于Java 与服务器的有限连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28367703/

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