Search code examples
socketswebsocketwebsocket-sharp

How to send data from web socket server to client?


I started using WebSocketSharp to create a simple WebSocket Server. Everything works great with this simple code:

var service = new WebSocketCustomerImageService();

var serverSocket = new WebSocketServer("ws://localhost:2000");
serverSocket.AddWebSocketService<WebSocketCustomerImageService>("/customerImageService");
serverSocket.Start();

Service class:

    public class WebSocketCustomerImageService : WebSocketBehavior
    {
        protected override void OnMessage(MessageEventArgs e)
        {
            Send("Hello from the other side!");
        }        
    }

This works great, the server responds when the client sends any message, but now, I want the server to send a message without the need of the client to send anything. The Send() method seems to only be available on the WebSocketBehavior class and I don't directly instanciate this WebSocketCustomerImageService class.

How can access the created instance to use the Send() method or what's the proper way to achieve this?


Solution

  • Ok solved it using:

    serverSocket.WebSocketServices["/customerImageService"].Sessions.Broadcast("My data");
    

    This sends "My data" to all clients listening on /customerImageService