sta / websocket-sharp

A C# implementation of the WebSocket protocol client and server
http://sta.github.io/websocket-sharp
MIT License
5.69k stars 1.66k forks source link

How can I send message to a specificate client? #751

Open philwu opened 4 months ago

philwu commented 4 months ago

Let's see, I already had a running websocket server. How can I take the initiative to send a message to one of them?

Currently, I can only:

Wait a message from a client and make response, or Make a broadcast so every client can receive the message. But what I want is sending to a client its own message by some logic.

Anyone help, please.

GholibjonMadiyarov commented 4 months ago

`server = new WebSocketServer(IPAddress.Any, 8000, true); server.SslConfiguration.ServerCertificate = new X509Certificate2("file", "password"); server.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Default | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12;

server.AddWebSocketService("/Web"); server.AddWebSocketService("/Desktop"); server.AddWebSocketService("/Mobile");

server.Log.File = AppDomain.CurrentDomain.BaseDirectory + "/ServerLog.txt"; server.KeepClean = false;

server.Start();

//Client id from db or file string clientId = "9b0d327304bc433cb2c1968720cd2792";

//Message data string message = "Hi!";

if (server.WebSocketServices["/Desktop"].Sessions.TryGetSession(clientId, out IWebSocketSession session)) { //Client is open if (session.State == WebSocketSharp.WebSocketState.Open) { server.WebSocketServices["/Desktop"].Sessions.SendTo(message, clientId); //session.Context.WebSocket.Send(message); } }`