문제

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

}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top