- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是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/
我有一个关于复杂性的简单问题。我在 Java 中有这段代码: pairs是 HashMap包含 Integer作为键,它的频率为 Collection作为一个值。所以: pairs = new Has
对于我的应用程序,我需要在 Coq 中使用和推理有限映射。谷歌搜索我发现 FMapAVL 似乎非常适合我的需求。问题是文档很少,我还没有弄清楚我应该如何使用它。 作为一个简单的例子,考虑以下使用对列表
我有一个主表tblAssetMaster A和一个移动表tblMovement M。 我想提取所有 Assets 及其当前位置,因此需要获取每个 Assets 的最新移动条目。 字段 A: Asset
我想让我的网站内容居中,但仅限于网页的特定宽度。所以当它超过 500px 时,我希望内容被修复,无法进一步拉伸(stretch)。无论如何都要这样做,还是我最好把所有东西都修好?希望有意义的是添加一些
我正在尝试批量删除 Backbone 模型的集合,如下所示...... collection.each(function(model, i){ model.destroy(); }); 我发现当每
我想要一个软件环境,在其中我可以在具有特定资源的硬件上测试我的软件的速度。例如,当我的主机硬件是具有 12GB RAM 的 3GHz 四核 amd64 时,该程序在具有 24 Mb RAM 的 800
在 Eclipse 中,我得到了 BigInteger.valueOf(2).pow(31093) 的值,但没有得到 BigInteger.valueOf(2).pow(31094) 的值(它是空的)
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 要求提供代码的问题必须表现出对所解决问题的最低限度理解。包括尝试过的解决方案、为什么它们不起作用,以及预
我想将 2 个表从本地 sql server 2000 上传到托管的 mysql。第一个表有 17 列和 680 行,其他 10 列和 8071 行。 我首先使用 xampp mysql 尝试离线,它
我在 S3 中自动生成并保存了静态 html 文件。有时文件大小达到 2mb。是否可以使用javascript来获取html文件的一部分,显示它,当用户到达页面底部时,获取下一部分等等? 最佳答案 X
我是一名优秀的程序员,十分优秀!