Java套接字侦听器



使用线程获取套接字的InputStream接收的对象,然后将它们添加到ConcurrentLinkedQueue中,这样就可以从主线程访问它们,而不会在轮询输入循环中阻塞它们,这合适吗?

private Queue<Packet> packetQueue = new ConcurrentLinkedQueue<Packet>();
private ObjectInputStream fromServer; //this is the input stream of the server
public void startListening()
{
    Thread listeningThread = new Thread()
    {
        public void run()
        {
            while(isConnected())    //check if the socket is connected to anything
            {
                try {
                    packetQueue.offer((Packet) fromServer.readObject());  //add packet to queue
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    listeningThread.start();  //start the thread 
}
public Packet getNextPacket()
{
    return packetQueue.poll();  //get the next packet in the queue
}

这取决于您需要对将在主线程中使用的对象执行什么操作。

如果需要某个时间来处理它,或者它的使用次数超过了您可以将它放入队列或另一个为您保存此对象的类的次数,但如果您需要处理它的时间很短,并且在处理后不需要进一步处理此对象,则您实际上不需要使用队列。

关于使用ConcurrentQueue也取决于,您需要订购吗?你需要保证读和写之间的同步吗?

您也可以使用异步套接字来处理同一线程中的许多客户端和进程,甚至可以从中获取对象并放入队列以进行进一步处理。

但是"适当"很难回答,因为这取决于你需要对这些对象做什么以及你将如何处理它

最新更新