0

目前我尝试实现一个服务器/客户端 - 应用程序并提出了一个问题,我找不到解决方案。

我正在运行 a Server,它正在等待Clients登录,将它们添加到 a并为每个cachedThreadPool启动一个新的,以处理他们的个人请求等。RunnableClient

现在对这些请求有一些答案,必须在服务器处理完之后广播。

        this.mOos = new ObjectOutputStream(this.mSocket.getOutputStream());
        this.mOos.flush();
        this.mOis = new ObjectInputStream(this.mSocket.getInputStream());

        while(true)
        {
            Object o = this.mOis.readObject();

            if(o !=null && this.mInputList.size() < 20)
            {
                this.mInputList.add(o);
            }

            if(!this.mInputList.isEmpty())
            {
                handleIncomingObject();
            }

            if(!this.mOutputList.isEmpty())
            {                       
                try 
                {
                    this.mOos.writeObject(this.mOutputList.remove(0));
                    this.mOos.flush();
                    this.mOos.reset();
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }               
        }

现在我遇到的问题是,当我处理请求时:

handleIncomingObject();

需要广播。

我的方法是在ExecutorService创建可运行对象时引用对象,以访问不同线程中的线程池。

如您所见,每个客户都有自己的

LinkedList<Object> mInputList
LinkedList<Object> mOutputList

缓冲传入和传出的消息。

handleIncomingObject()我想做类似的事情:

//assume exec as ExecutorService
for(Thread t : exec)
{
        mOutputList.add(new Message(message));
}

提前感谢任何帮助或建议。

问候,本。

4

1 回答 1

1

Use a Vector containing all clients and iterate over this Vector to send broadcast messages. You can use a method like:

public static synchronized void broadcast(Message msg) {
    for(Client c : vector) {
        c.mOutputList.add(msg);
    }
}
于 2014-06-15T13:16:06.807 回答