I am using WCF with duplex netTcpBinding and I want to send a message to all users connected currently to my service. 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’. 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.
So it seems each client has it’s own service/server.
- With that in mind how do I send a message to all my clients from the server?
- I thought the standard practise for accessing the server from the client was to get a proxy object, call the service functions, and then Close the proxy object like in the code above…but if I close the proxy object doesn’t it mean I have closed the connection between client and server and now the server won’t be able to make duplex callbacks to the client?
1) If you want all clients to share the same server, you need to make your service a singleton. Add this attribute to the class implementing your service (not the interface):
That said, I suspect that what you really want is a synchronized, static (thread-shared) instance of a
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. You need to keep the proxy open and stash them somewhere in the client. This design will of course significantly limit scalability.