监听多个套接字(InputStreamReader)
我在课堂上设计的一个小游戏遇到了问题。 问题是我有两个客户端连接到服务器。 (client1 和 client2)他们各自运行一个游戏,最终关闭窗口。由于游戏窗口是一个 JDialog,因此当它关闭时,它会通过套接字向服务器发送一条消息,告诉它已经完成。我希望服务器知道两个客户端中哪一个先完成。他们通过套接字的 OutputStream 上的 PrintWriter 进行报告。 我所做的是:
in1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
in2 = new BufferedReader(new InputStreamReader(client2.getInputStream()));
try {
in1.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in2.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
问题是它等待第一个输入,然后才开始监听第二个输入。我怎样才能让它同时收听两者?或者以其他方式解决我的问题。 谢谢!
I'm having a problem with a little game I'm designing in my class.
The problem is that I got two clients connected to a server. (client1 and client2) They are each running a game, which in the end, closes the window. As the game window is a JDialog, it will then, when it's closed, send a message, through a socket, to the server, telling it that it's done. I want the server to know which of the two clients were completed first. They are reporting through a PrintWriter on the sockets' OutputStream.
What I did was this:
in1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
in2 = new BufferedReader(new InputStreamReader(client2.getInputStream()));
try {
in1.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in2.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
Problem is that it waits for the first input, before it even starts listening on the second. How can I make it listen on both at the same time? Or solve my problem some other way.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务器连接应该像这样工作:
在 hanleConnection() 中,您启动一个新线程并在创建的线程中运行该客户端的通信。然后服务器可以接受新连接(在旧线程中)。
PlayerConnection 类:
Server connection should work like this:
In hanleConnection() you start a new thread and run the communication for this client in the created thread. Then the server can accept a new connection (in the old thread).
The PlayerConnection class: