/// <summary> /// Kills ship of client that disconnects and removes client from world /// </summary> /// <param name="ss"></param> public static void DisconnectClientHandler(Networking.SocketState ss, string message) { Console.WriteLine(message); Ship ship = TheWorld.GetShipAtId(ss.ID); ship.SetHp(0); SendWorld(); // make sure to send the world so that the client knows to terminate the ship. lock (TheWorld) { // remove ship and client connection associated with that ship. TheWorld.RemoveShipAll(ss.ID); ClientConnections.Remove(ss.ID); } }
public override async Task RunServerLoop() { if (ServerStarted) { return; } ServerStarted = true; Task cancelTask = Task.Run(() => WaitHandle.WaitAny(new[] { TokenSource.Token.WaitHandle })); using (HttpListener listener = new HttpListener()) { listener.Prefixes.Add(Uri.ToString()); listener.Start(); while (!TokenSource.IsCancellationRequested) { Task <HttpListenerContext> listenerContextTask = listener.GetContextAsync(); int index = Task.WaitAny(cancelTask, listenerContextTask); if (index == 0) { break; } HttpListenerContext listenerContext = listenerContextTask.Result; if (!listenerContext.Request.IsWebSocketRequest) { listenerContext.Response.StatusCode = 400; listenerContext.Response.Close(); } else { HttpListenerWebSocketContext webSocketContext = await listenerContext.AcceptWebSocketAsync(null); WebSocketConnection ws = new ClientConnection(webSocketContext.WebSocket, listenerContext.Request.RemoteEndPoint?.ToString()); ClientConnections.Add(ws); ws.OnMessage += (e, a) => InvokeOnMessage(a); ws.OnError += (e, a) => InvokeOnError(a); ws.OnClose += (e, a) => { InvokeOnClose(a); ClientConnections.Remove(a.Connection); }; InvokeOnClientConnected(new OnClientConnectedEventArgs(ws)); } } } cancelTask.Wait(); ServerStopEvent.Set(); }
public void RemoveConnection(string index, TcpClient c) { ClientConnections.Remove(index.ToUpper()); }