如何使Java中的线程等待两个不同的输入流发生变化?

huangapple go评论72阅读模式
英文:

How to make a Thread in Java wait for two different inputStreams to change?

问题

在当前代码中,当一个客户端发送消息时,该消息被重新发送给其他客户端。为了满足你描述的需求,你需要修改代码以便在以下两种情况下等待:

  1. 客户端发送消息
  2. 另一个线程发送消息到该线程

修改后的代码可能如下所示:

// 在服务器端的主循环中
while (true) {
    // 等待客户端连接
    Socket clientSocket = serverSocket.accept();
    // 创建一个线程来处理该客户端
    Thread clientThread = new Thread(new ClientHandler(clientSocket));
    clientThread.start();
}

// ClientHandler 类中的代码
class ClientHandler implements Runnable {
    private Socket clientSocket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
        try {
            this.inputStream = socket.getInputStream();
            this.outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                // 处理客户端发送的消息
                // ...

                // 发送消息给其他客户端
                synchronized (otherclientSockets) {
                    for (Socket otherclientSocket : otherclientSockets) {
                        if (!clientSocket.equals(otherclientSocket)) {
                            otherclientSocket.getOutputStream().write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个修改后的代码中,每个客户端连接都会有一个对应的 ClientHandler 线程,该线程负责处理客户端的输入和输出。当一个客户端发送消息时,该消息将被 ClientHandler 线程处理,并发送给其他客户端。同时,每个 ClientHandler 线程都在循环中等待从其他线程接收消息。

英文:

I am creating a program where there is a Server and many Clients. When a client connects to the server a thread is created to manage that client. Whenever a client sends a message the thread receives this message and sends it to the rest of threads. When a thread receives a message from another thread sends it to its client.

The problem I am having is that for this purpose one thread needs to wait for two different conditions at the same time:

  1. A client sends a message
  2. Another thread sends a message to that thread

The code I have right now is:

byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
synchronized (otherclientSockets) {
for (Socket otherclientSocket : otherclientSockets) {
if (!clientSocket.equals(otherclientSocket)) {
otherclientSocket.getOutputStream().write(buffer, 0, bytesRead);
}
}
}

Right now when a thread receives the message from the client it resends the message to the rest of clients. How can I change this in order to work as described before?

Thank you 如何使Java中的线程等待两个不同的输入流发生变化?

答案1

得分: 2

Java中的正常模式是为每个客户端创建一个线程。一个线程不能同时等待多个InputStream。

如果你想在同一个线程上等待多个事物,你可以使用NIO进行“升级”。然后,你可以创建一个 Selector,使用选择器来 注册 你的通道(流 - 你必须使用SocketChannel而不是InputStream/OutputStream),并使用选择器来 等待 一个或多个通道有数据,都在同一个线程上。选择器还有一个 wakeup 方法,可以立即停止等待,以防你希望出于与通道无关的原因停止等待。

英文:

The normal pattern in Java is to make a thread per client. One thread can't wait for more than one InputStream at the same time.

If you want to wait for more than one thing on the same thread, you can "upgrade" to NIO. Then you can create a Selector, register your channels (streams - you have to use SocketChannel instead of InputStream/OutputStream) with the selector, and wait for one or more to have data, all on one thread. The selector also has a wakeup method which causes it to stop waiting immediately, in case you want it to stop waiting for a reason that has nothing to do with channels.

huangapple
  • 本文由 发表于 2023年5月22日 21:53:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定