Last active
March 23, 2022 04:35
-
-
Save nzhul/2969ac49a2e47c57ac5ff5f0b72d7b01 to your computer and use it in GitHub Desktop.
Example of simple WebSockets server using Fleck
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Javascript example | |
$(function(){ | |
var webSocket = window.WebSocket || window.MozWebSocket, | |
ws = new webSocket('ws://localhost:8181'); | |
ws.onopen = function(e){ | |
console.log('Connection opened'); | |
} | |
ws.onclose = function(e){ | |
console.log('Connection closed'); | |
} | |
ws.onmessage = function(e){ | |
var dataObject = JSON.parse(e.data); | |
console.log(dataObject); | |
} | |
}); | |
........ | |
// Server side | |
Main() | |
{ | |
HelloServer server = new HelloServer(); | |
server.Start(); | |
} | |
public void Start() | |
{ | |
List<IWebsocketConnection> sockets = new List<IWebsocketConnection>(); | |
Fleck.WebSocketServer server = new Fleck.WebSocketServer("ws://localhost:8181"); | |
server.Start(socket => | |
{ | |
socket.OnOpen = () => | |
{ | |
Console.WriteLine("Connection open."); | |
sockets.Add(socket); | |
}; | |
socket.OnClose = () => | |
{ | |
Console.WriteLine("Connection closed."); | |
sockets.Remove(socket); | |
}; | |
socket.OnMessage = message => | |
{ | |
Console.WriteLine("Client Says: " + message); | |
sockets.ToList().ForEach(s => s.Send(" client says: " + message)) | |
}; | |
}); | |
string input = Console.ReadLine(); | |
while(input != "exit") | |
{ | |
sockets.ToList().ForEach(s => s.Send(input)); | |
input = Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Helpful, thanks