简体   繁体   English

Java Nio服务器客户端异步

[英]Java nio server client asynchonous

I made a server myself using java nio and a selector. 我自己使用java nio和选择器制作了服务器。 I can receive the data and answer directly from the client if needed. 如果需要,我可以直接从客户端接收数据并回答。

But now I want a thread that will process data, and anytime it will send data to each client. 但是现在我想要一个线程来处理数据,并且随时随地将数据发送到每个客户端。

So how can I do that? 那我该怎么办呢? Also how to keep in memory all channels to write the data to each client ? 还有如何将所有通道保存在内存中以将数据写入每个客户端?

If you need I can post the part of my code with java nio. 如果需要,我可以使用java nio发布部分代码。

Create a new thread with a runnable and make sure it knows your server because your server should know all clients. 创建一个具有可运行线程的新线程,并确保它知道您的服务器,因为您的服务器应该知道所有客户端。 If a client sends a message parse it through the data processor thread and let it do it's job. 如果客户端发送一条消息,则通过数据处理器线程对其进行解析,然后让它完成工作。 When it's done processing your task then let the server know so he can update all clients. 处理完任务后,请通知服务器,以便他可以更新所有客户端。

Tip: you should make a waiting queue for the processing thread with something like a LinkedBlockingQueue so you can always put tasks on the queue without waiting for the task to finish. 提示:您应使用LinkedBlockingQueue之类的东西为处理线程创建一个等待队列,以便始终可以将任务放在队列中,而无需等待任务完成。 Then the thead will wait for things on the queue that need to be processed. 然后,thead将等待队列中需要处理的内容。 This way the processing thread will only use CPU resources when there are actually tasks on the queue 这样,处理线程仅在队列中实际有任务时才使用CPU资源

Here is a code example 这是一个代码示例

public abstract class Queue implements Runnable {
private final LinkedBlockingQueue<Message> queue;

public Queue() {
    this.queue = new LinkedBlockingQueue<Message>();
}

/**
 * Adds a message to the queue.
 * @param message
 */
public void add(final Message message) {
    try {
        queue.put(message);
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }
}

/**
 * Waits for new messages
 */
@Override
public void run() {
    while(true) {
        try {
            final Message message = queue.take();
            processMessage(message);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/**
* Processes the new message
*/
protected abstract void processMessage(Message message);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM