[英]WCF duplex callbacks, how do I send a message to all clients?
I am using WCF with duplex netTcpBinding
and I want to send a message to all users connected currently to my service. 我正在使用WCF与双工
netTcpBinding
,我想向当前连接到我的服务的所有用户发送一条消息。 I thought I could just create a callback contract and it would send a message to all the clients but it seems I am mistaken, and there isn't a single server/service, each client gets its own service? 我以为我可以创建一个回调合约,它会向所有客户发送一条消息,但似乎我错了,并且没有一个服务器/服务,每个客户端都有自己的服务?
I have service with the name 'Server'. 我的服务名称为'Server'。 Here is how I access the server from the client -
以下是我从客户端访问服务器的方法 -
ServerClient client = new ServerClient();
string result = client.SendMessage(messageTextBox.Text);
client.Close();
I thought the 'Server' was a single object that handled all calls by my clients but then I've started a thread in the Server constructor and I found out that multiple threads get started because every time a client calls the Server, a new Server object is created. 我认为'Server'是一个单个对象来处理我的客户端的所有调用,但后来我在Server构造函数中启动了一个线程,我发现多个线程都启动了,因为每次客户端调用Server时,都会有一个新的服务器对象已创建。
So it seems each client has it's own service/server. 所以似乎每个客户端都有自己的服务/服务器。
1) If you want all clients to share the same server, you need to make your service a singleton. 1)如果您希望所有客户端共享同一台服务器,您需要使您的服务成为单身人士。 Add this attribute to the class implementing your service (not the interface):
将此属性添加到实现服务的类(而不是接口):
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
That said, I suspect that what you really want is a synchronized, static (thread-shared) instance of a List<ServerClient>
. 也就是说,我怀疑你真正想要的是
List<ServerClient>
的同步,静态(线程共享)实例。 Then you would iterate over that to send a message to each client. 然后,您将迭代它以向每个客户端发送消息。 With that design, you wouldn't need a singleton server (just some good thread safety around the list).
使用该设计,您不需要单一服务器(只需在列表周围提供一些良好的线程安全性)。
2) If the clients close their server proxies, the server will not be able to send them any messages. 2)如果客户端关闭其服务器代理,服务器将无法向其发送任何消息。 You need to keep the proxy open and stash them somewhere in the client.
您需要保持代理打开并将其存储在客户端的某个位置。 This design will of course significantly limit scalability.
这种设计当然会显着限制可扩展性。
By default each client will get its own instance of the service. 默认情况下,每个客户端都将获得自己的服务实例。 You can however make your service a singleton (which will than process requests from all client).
但是,您可以使您的服务成为单一服务(这将处理来自所有客户端的请求)。
You may also want to skim through this Instance management article 您可能还想浏览此实例管理文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.