Skip to content

Instantly share code, notes, and snippets.

@vkobel
Last active August 29, 2015 13:57
Show Gist options
  • Save vkobel/9915309 to your computer and use it in GitHub Desktop.
Save vkobel/9915309 to your computer and use it in GitHub Desktop.
Basic structure for a WebSocket communication (multitask ready) with C# / Alchemy
$ ->
ws = new WebSocket "ws://localhost:81"
ws.onmessage = (evt) ->
console.log evt
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Alchemy;
using Alchemy.Classes;
namespace WebSocketsDemo {
class WSServer {
private WebSocketServer server;
private static ConcurrentDictionary<int, UserContext> Clients = new ConcurrentDictionary<int, UserContext>();
private UserContext nul = null;
public WSServer() {
server = new WebSocketServer(81, IPAddress.Any) {
OnConnected = (UserContext user) => Clients.TryAdd(user.GetHashCode(), user),
OnDisconnect = (UserContext user) => Clients.TryRemove(user.GetHashCode(), out nul)
};
}
public void Start() {
server.Start();
int i = 0;
Task.Factory.StartNew(() => {
while(true) {
Console.WriteLine(Clients.Count + " clients");
foreach(var u in Clients)
u.Value.Send("iteration nb " + i);
i++;
Thread.Sleep(1000);
}
});
var command = string.Empty;
while(command != "exit")
command = Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment