gpt4 book ai didi

java - 监听多个套接字 (InputStreamReader)

转载 作者:行者123 更新时间:2023-11-29 06:44:18 28 4
gpt4 key购买 nike

我在类里面设计的一个小游戏有问题。问题是我有两个客户端连接到服务器。 (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);
}

问题是它等待第一个输入,甚至在它开始监听第二个输入之前。我怎样才能让它同时收听两者?或者以其他方式解决我的问题。谢谢!

最佳答案

服务器连接应该是这样的:

Server gameServer = new Server();

ServerSocket server;
try {
server = new ServerSocket(10100);
// .. server setting should be done here
} catch (IOException e) {
System.out.println("Could not start server!");
return ;
}

while (true) {
Socket client = null;
try {
client = server.accept();
gameServer.handleConnection(client);
} catch (IOException e) {
e.printStackTrace();
}
}

在 hanleConnection() 中,您启动一​​个新线程并在创建的线程中为该客户端运行通信。然后服务器可以接受新连接(在旧线程中)。

public class Server {
private ExecutorService executor = Executors.newCachedThreadPool();

public void handleConnection(Socket client) throws IOException {
PlayerConnection newPlayer = new PlayerConnection(this, client);
this.executor.execute(newPlayer);
}

// add methods to handle requests from PlayerConnection
}

PlayerConnection 类:

public class PlayerConnection implements Runnable {

private Server parent;

private Socket socket;
private DataOutputStream out;
private DataInputStream in;

protected PlayerConnection(Server parent, Socket socket) throws IOException {
try {
socket.setSoTimeout(0);
socket.setKeepAlive(true);
} catch (SocketException e) {}

this.parent = parent;
this.socket = socket;

this.out = new DataOutputStream(socket.getOutputStream());;
this.in = new DataInputStream(socket.getInputStream());
}

@Override
public void run() {
while(!this.socket.isClosed()) {
try {
int nextEvent = this.in.readInt();

switch (nextEvent) {
// handle event and inform Server
}
} catch (IOException e) {}
}

try {
this.closeConnection();
} catch (IOException e) {}
}
}

关于java - 监听多个套接字 (InputStreamReader),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7661130/

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