简体   繁体   中英

Java nio server client asynchonous

I made a server myself using java nio and a selector. 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.

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. Then the thead will wait for things on the queue that need to be processed. This way the processing thread will only use CPU resources when there are actually tasks on the queue

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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