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-Package WebSocketSharp
Below was the full WebSocket server program is listed below.
WebSocket - Server
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace WebSockets.Server.App
{
class Program
{
static void Main(string[] args)
{
var wssv = new WebSocketServer("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();
}
}
public class Laputa : WebSocketBehavior
{
protected override void OnMessage(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.
WebSocket - Client
using System;
using WebSocketSharp;
namespace WebSockets.Client.App
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press Enter to Start Client");
Console.Read();
using (var ws = new WebSocket("ws://localhost:7569/Laputa"))
{
ws.OnMessage += (sender, e) =>
Console.WriteLine("Laputa says: " + e.Data);
ws.Connect();
ws.Send("BALUS");
Console.WriteLine("Client Started.");
Console.ReadKey(true);
}
}
}
}
Client 2 - JS Client
The below code uses the JavaScript Client which receives message from the server.
WebSocketClient.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Web Socket JS Client</title>
<script>
"use strict";globalThis.__codeBoxId = "zy3koqx4bh";
let socket = new WebSocket("ws://localhost:7569/Laputa");
socket.onopen = function(e) {
alert("[open] Connection established");
alert("Sending to server");
socket.send("BALUS");
};
socket.onmessage = function(event) {
alert(`[message] Data received from server: ${event.data}`);
};
socket.onclose = function(event) {
if (event.wasClean) {
alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
alert('[close] Connection died');
}
};
socket.onerror = function(error) {
alert(`[error] ${error.message}`);
};
</script>
</head>
<body>
</body>
</html>