[英]Broadcasting Objects to multiple clients
Currently I try to implement a Server/Client - Application and came up with a problem, I cant find a solution for. 目前,我尝试实现服务器/客户端-应用程序,并提出了一个问题,但找不到解决方案。
Im running a Server
, which is waiting for Clients
to login, adding them to a cachedThreadPool
and starting a new Runnable
for each Client
, to handle their individual requests etc. 我正在运行一个
Server
,等待Clients
登录,将它们添加到cachedThreadPool
并为每个Client
启动一个新的Runnable
,以处理其各自的请求等。
Now there are some answers to these requests, which have to be broadcasted after the server did his processing. 现在,对这些请求有一些答案,必须在服务器进行处理后广播这些答案。
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();
}
}
}
Now what I'm having trouble with is, that when I process a request in: 现在,我遇到的麻烦是,当我在其中处理请求时:
handleIncomingObject();
which needs to be broadcasted. 需要广播。
My approach is to give a reference to the ExecutorService
Object, when I create the runnable, to have access to the threadpool IN the different threads. 我的方法是在创建可运行对象时提供对
ExecutorService
对象的引用,以访问不同线程中的线程池。
As you may see, every client got his own 如您所见,每个客户都有自己的
LinkedList<Object> mInputList
LinkedList<Object> mOutputList
to buffer incoming and outgoing messages. 缓冲传入和传出的消息。
In handleIncomingObject()
I'd like to do something like: 在
handleIncomingObject()
我想执行以下操作:
//assume exec as ExecutorService
for(Thread t : exec)
{
mOutputList.add(new Message(message));
}
Thanks in advance any every help or suggestions. 在此先感谢您的任何帮助或建议。
Greetings, Ben. 问候,本。
Use a Vector containing all clients and iterate over this Vector to send broadcast messages. 使用包含所有客户端的Vector,并在此Vector上进行迭代以发送广播消息。 You can use a method like:
您可以使用如下方法:
public static synchronized void broadcast(Message msg) {
for(Client c : vector) {
c.mOutputList.add(msg);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.