WCF duplex callbacks, how to send a message to all clients?

I am using WCF with netTcpBinding duplex and I want to send a message to all users currently connected to my service. I thought I could just create a callback contract, and it will send a message to all clients, but it seems like I'm wrong, and there is not a single server / service, each client gets its own service?

I have a service called "Server". This is how I access the server from the client -

 ServerClient client = new ServerClient(); string result = client.SendMessage(messageTextBox.Text); client.Close(); 

I thought that the β€œServer” was the only object that handled all the calls of my clients, but then I started the thread in the Server constructor and I found out that several threads are starting, because every time the client calls the Server, a new server object is created .

So, each client has its own service / server.

  • With this in mind, how to send a message to all my clients from the server?
  • I thought the standard practice of accessing the server from the client was to get a proxy object, call utility functions and then close the proxy object, as in the code above ... but if I close the proxy object, This means that I closed the connection between the client and the server, and now the server will not be able to make two-way callbacks to the client?
+1
source share
2 answers

1) If you want all clients to have shared access to the same server, you need to make your service a single. Add this attribute to the class that implements your service (and not the interface):

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 

However, I suspect that you really need a synchronized, static (shared stream) instance of List<ServerClient> . Then you will forward the message to each client. With this design, you will not need one single server (just good stream security around the list).

2) If clients close their proxies, the server will not be able to send them any messages. You need to leave the proxies open and sew them somewhere in the client. This design, of course, will significantly limit scalability.

+3
source

By default, each client will receive its own instance of the service. However, you can make your service a singleton (which will handle requests from the entire client).

You can also view this instance management article.

+1
source

Source: https://habr.com/ru/post/1387107/


All Articles