Last active
August 29, 2015 13:57
-
-
Save vkobel/9915309 to your computer and use it in GitHub Desktop.
Basic structure for a WebSocket communication (multitask ready) with C# / Alchemy
This file contains hidden or 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
$ -> | |
ws = new WebSocket "ws://localhost:81" | |
ws.onmessage = (evt) -> | |
console.log evt |
This file contains hidden or 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
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