Skip to content

Instantly share code, notes, and snippets.

@nzhul
Last active March 23, 2022 04:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nzhul/2969ac49a2e47c57ac5ff5f0b72d7b01 to your computer and use it in GitHub Desktop.
Save nzhul/2969ac49a2e47c57ac5ff5f0b72d7b01 to your computer and use it in GitHub Desktop.
Example of simple WebSockets server using Fleck
// 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();
}
}
@0xGREG
Copy link

0xGREG commented Mar 17, 2019

Helpful, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment