Question

Can anyone provide examples in Java, or advise about implementing a class which asynchronously reads lines from a socket and puts each line into a BlockingQueue. Assume the socket is connected, and the BlockingQueue and consumer already exists.

Edit: One more thing, it needs to have the ability to timeout after a period of inactivity, and stop immediately on command.

It's not homework, I simply have not been able to find complete examples for how to do this well, and reliably.

Thank you very much.

Was it helpful?

Solution

You sound like you've already done the work, to be honest. All you need to do is create a BlockingQueue and have a thread to process it which is your consumer I guess. Assuming you have a DataInputStream 'in'...

Something like this:

BlockingQueue<String> receivedQueue = new LinkedBlockingQueue<String>();
public void run()
{
    while (true)
    {
        try
        {
            receivedQueue.put(in.readUTF());
        } catch (EOFException e)
        {
            ch.getClient().disconnect();
            break;
        } catch (IOException e)
        {
            break;
        } catch (InterruptedException e)
        {
            break;
        }
    }
    theQueueProcessor.interrupt();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top