문제

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.

도움이 되었습니까?

해결책

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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top