Using Web Socket send message from server to client and client to server Client(JS Client & Console Client)
Server -WebSocket Program - Console Application
Our WebSocket program runs as a console application, it uses WebSocketSharp nuget library to achieve the WebSocket Send and receive, the Library code is available in the GitHub.
Nuget installation
Install-PackageWebSocketSharp
Below was the full WebSocket server program is listed below.
WebSocket - Server
usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceWebSockets.Server.App{classProgram {staticvoidMain(string[] args) {var wssv =newWebSocketServer("ws://localhost:7569");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.WriteLine("Server Started");int iCount =0;while (true) {string key =Console.ReadLine();if (key =="x") {break; }else { iCount++;wssv.WebSocketServices.Broadcast("Serv Message "+ iCount);//Sends message to Web Client. } }Console.ReadKey(true);wssv.Stop(); } }publicclassLaputa:WebSocketBehavior {protectedoverridevoidOnMessage(MessageEventArgs e) {var msg =e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);Console.WriteLine("Server Message {0}", msg); } }}
The above application is a console application and it acts as a WebSocket Server.
Client 1 - Console Application - Client
The below example, shows that the console application client which connects to the server and reverts the message.