Client side is easiest part, javascript, in my case looks something like this:
var ws; window.onload = function () { if ("WebSocket" in window) { // Let us open a web socket ws = new WebSocket("ws://127.0.0.1:9192"); ws.onmessage = function (evt) { Log(evt.data) }; ws.onclose = function() { // websocket is closed. Log("Connection is closed..."); }; } else { // The browser doesn't support WebSocket Log("WebSocket NOT supported by your Browser!"); } } function WebSocketSendMessage() { ws.send(document.getElementsByName("inputSend")[0].value); } function Log(message) { document.getElementsByName("log")[0].innerHTML = document.getElementsByName("log")[0].innerHTML + '<br/>' + message; }
To create new Socket use code:
ws = new WebSocket("ws://127.0.0.1:9192"); - note that here I defined IP address and port, later you will see that in C# code I also defined on which IP address and port server will listen messages.
Event onmessage will be triggered when message is received, and to send message use method send, and that is all.
Simple example of WebSockets in C# I did it with Fleck, you can use NuGet to add it to references:
Create new console application, write code like:
namespace WebSocket { using System; using Fleck; public class Program { static void Main(string[] args) { var server = new WebSocketServer("ws://127.0.0.1:9192"); server.Start(socket => { socket.OnOpen = () => Console.WriteLine("Listening... "); socket.OnClose = () => Console.WriteLine("Closed!"); socket.OnMessage = message => { Console.WriteLine(message); }; }); Console.ReadLine(); } } }
Notice:
var server = new WebSocketServer("ws://127.0.0.1:9192"); - as I wrote before this is IP address and port on which server listens messages.
I implemented OnMessage event which will trigger when message from the client arrives.