using NetCoreServer; using System.Drawing; using System; using System.Text; using System.Linq; using System.Collections.Generic; using System.Net.Sockets; namespace websocketserver.Library { class UserSession : WsSession { private ChatServer server; private string channelKey; private string userKey; private string roomKey; private PointF position; public UserSession(ChatServer server) : base(server) { this.server = server; this.channelKey = "room-0,0"; this.userKey = ""; this.roomKey = "room-0,0"; this.position = new PointF(0.5F, 0.5F); } public string GetChannel() { return this.channelKey; } public void SetChannel(string key) { this.channelKey = key; } public PointF GetPosition() { return this.position; } public string GetUserKey() { return this.userKey; } public string GetRoomKey() { return this.roomKey; } public override void OnWsConnected(HttpRequest request) { Console.WriteLine($"Chat WebSocket session with Id {Id} connected!"); // string message = "connected"; // SendTextAsync(message); } public override void OnWsDisconnected() { Console.WriteLine("User {0} disconnected", this.GetUserKey()); this.server.Disconnect(this); } public override void OnWsReceived(byte[] buffer, long offset, long size) { string message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); string[] splitMessage = message.Split(" "); string command = splitMessage[0]; switch (command) { case "subscribe": this.userKey = splitMessage[1]; this.roomKey = splitMessage[2]; Console.WriteLine("User {0} joining {1}", this.GetUserKey(), this.GetRoomKey()); this.server.Subscribe(this.roomKey, this); break; case "move": this.userKey = splitMessage[1]; this.position.X = float.Parse(splitMessage[2]); this.position.Y = float.Parse(splitMessage[3]); this.server.Move(this); break; case "chat": this.server.Chat(this, string.Join(" ", splitMessage.Skip(1).ToArray())); break; case "quit": Close(1000); break; default: Console.WriteLine("Incoming: {0}", message); this.server.MulticastText(message); break; } } protected override void OnError(SocketError error) { Console.WriteLine($"Chat WebSocket session caught an error with code {error}"); } } }