/// <summary> /// This is the event handler attached to every client that is connected's MessageReceive event. /// This is where it checks if a client has sent the disconnetion code, and if so, disposes of them. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ConnectedClient_MessageReceived(object sender, MessageReceivedEventArgs e) { if (e.Message == TcpOptions.EndConnectionCode.ToString()) { ConnectedClients.Remove(sender as Client); var eventargs = new ClientToggleEventArgs { ConnectedClient = sender as Client, Time = DateTime.Now }; ClientDisconnected?.Invoke(this, eventargs); } else { foreach (var response in Responses) { var willTrigger = false; switch (response.Mode) { case ContentMode.Contains: if (e.Message.Contains(response.Content)) { willTrigger = true; } break; case ContentMode.EndsWish: if (e.Message.EndsWith(response.Content)) { willTrigger = true; } break; case ContentMode.StartsWith: if (e.Message.StartsWith(response.Content)) { willTrigger = true; } break; case ContentMode.Equals: if (e.Message == response.Content) { willTrigger = true; } break; } if (willTrigger) { response.Event?.Invoke(e); } else { MessageReceived?.Invoke(sender, e); } } } }
public void Close() { ms.Close(); ms.Dispose(); tcpClient.Close(); ClientDisconnected?.Invoke(this); }
public override async Task WaitForConnectionsAsync(CancellationToken token) { if (iteration % 2 == 0) { if (ClientConnected != null) { ClientConnected.Invoke(this, new IpcServerClientConnectedEventArgs()); } } if (iteration % 3 == 0) { if (ClientDisconnected != null) { ClientDisconnected.Invoke(this, new IpcServerClientDisconnectedEventArgs()); } } if (iteration < IterationCount) { Interlocked.Increment(ref iteration); } else { this.Cancel(); } await Task.CompletedTask; }
/// <summary> /// Fires the ClientDisconnected event. /// </summary> /// <param name="client">Client that disconnected</param> public void FireClientDisconnected(Client client) { PluginUtils.ProtectedInvoke(() => { ClientDisconnected?.Invoke(client); }, "ClientDisconnected"); }
void HandleClient(TcpClient client) { var tcpClient = client; var stream = tcpClient.GetStream(); ClientConnected?.Invoke(client); var message = new byte[4096]; while (true) { var bytesRead = 0; try { bytesRead = stream.Read(message, 0, 4096); } catch { /* Clause not empty now, is it ReSharper? Haha! */ } // Client disconnected if (bytesRead == 0 || !ServerRunning) { ClientDisconnected?.Invoke(client); break; } var fullMessage = new ASCIIEncoding().GetString(message, 0, bytesRead).Replace("\r", "").Replace("\n", ""); InvokeOnCommandRecieved(fullMessage, tcpClient); } }
private void Run() { var buffer = new byte[1024]; while (!_stop) { try { var readCount = Socket.Receive(buffer); if (readCount == 0) { break; } var text = Encoding.UTF8.GetString(buffer, 0, readCount); Console.WriteLine($"Client sent: {text}"); Socket.Send(buffer, 0, readCount, SocketFlags.None); } catch (Exception ex) { Console.WriteLine(ex); break; } Thread.Sleep(1); } ClientDisconnected?.Invoke(this, EventArgs.Empty); }
private void WebSocketPacketReceived(Packet packet) { lock (syncObject) { switch (packet.Action) { case WebSocketAction.Connect: ClientConnected?.Invoke(packet.RemoteEndPoint, ((ConnectionPacket)packet).Cookies); break; case WebSocketAction.SendText: ClientSendText?.Invoke(packet.RemoteEndPoint, packet.Text); break; case WebSocketAction.Disconnect: var client = webSocketClients.FirstOrDefault(c => c.RemoteEndPoint.Equals(packet.RemoteEndPoint)); if (client != null) { client.Disconnect(4000, "Responding to client's request to close the connection."); webSocketClients.Remove(client); ClientDisconnected?.Invoke(packet.RemoteEndPoint, packet.Text); } break; default: throw new NotImplementedException(); } } }
private void OnClientDisconnected(ITcpProtocolClient client_) { UnsubscribeFromClientEvents(client_); _clientList.Remove(client_); ClientDisconnected?.Invoke(this, client_); }
// Disconnect a client; returns true if successful private bool DisconnectClient(IPEndPoint endPoint) { // Get all EndPoints/Sockets where the endpoint matches with this argument var filtered = Sockets.Where(c => c.Key.Equals(endPoint)).ToArray(); // .count should always be 1, CAN be more -> Loop foreach (KeyValuePair <IPEndPoint, Socket> kvp in filtered) { try { kvp.Value.Disconnect(false); // Gracefully disconnect socket kvp.Value.Close(); kvp.Value.Dispose(); Sockets.Remove(kvp.Key); // Remove from collection ClientDisconnected?.Invoke(kvp.Key); // Event } catch { // Socket is either already disconnected, or failing to disconnect. try ping return(!kvp.Value.Ping()); } } return(true); }
/// <summary> /// Configures a new server-side client connection /// </summary> /// <param name="client">The new server-side client connection</param> protected virtual void OnCreateClientHandler(TcpClient client) { //var handler = new TClientType(client); var handler = CreateClient(client);// (TClientType)Activator.CreateInstance(typeof(TClientType), client); handler.Disconnected += (s, remoteEndPoint, exception) => { if (_clients.Contains(handler)) { _clients.Remove(handler); } ClientDisconnected?.Invoke(handler, remoteEndPoint, exception); }; //Notifications.ClientCreated?.Invoke(handler); //handler.As<IFormattedSocket>().Disconnected += (s, remoteEndPoint, exception) => //{ // var proxy = s.As<TClientType>(); // if (proxy == null) // throw new ArgumentOutOfRangeException(nameof(s), "Parameter s should have been a legitimate instance of SecureByteClient"); // if (_clients.Contains(proxy)) // _clients.Remove(proxy); // ClientDisconnected?.Invoke(proxy, remoteEndPoint, exception); //}; _clients.Add(handler); ClientConnected?.Invoke(handler); System.Diagnostics.Debug.WriteLine("Server created client handler"); }
// public void Start() { _listener = new TcpListener(IPAddress.Any, 8008); _listener.Start(1); while (!_stopRequested) { _remoteClient = _listener.AcceptTcpClient(); ClientConnected?.Invoke(this, new RemoteClient { IpAddress = _remoteClient.IpAddress(), Connected = true }); while (!_stopRequested) { if (_remoteClient.Available > 0) { HandleRequest(); } if (!Connected()) { ClientDisconnected?.Invoke(this, new RemoteClient { IpAddress = _remoteClient.IpAddress(), Connected = true }); ResetState(); break; } } } }
private void ConnectionOnTerminatedUnexpectedly() { _isTerminating = true; try { foreach (var kvp in _clientSessions) { var session = kvp.Value; try { _log.Info($"Disconnected client due to unhandled error: {session}"); ClientDisconnected?.Invoke(session.ToIdentity()); } catch (Exception ex) { _log.Error(ex); } } } finally { TerminatedUnexpectedly?.Invoke(); DisposeImpl(false); } }
/// <summary> /// Called when a client establishes a connection with the server. /// </summary> /// <param name="state">The client's socket state.</param> private void ClientConnectionEstablished(SocketState state) { // Add a new client communicator. var communicator = new ClientCommunicator(this, state); _clients.Add(communicator.Id, communicator); // Create a ship when the client sends their nickname. communicator.NicknameReceived += nickname => { var ship = new Ship(communicator.Id, nickname); _world.PutComponent(ship); }; // Handle the case where the client disconnects. communicator.Disconnected += () => { // Remove the client's ship. _world.GetComponent <Ship>(communicator.Id).Health = 0; // Remove the client communicator. _clients.Remove(communicator.Id); // Notify listeners. ClientDisconnected?.Invoke(); }; // Start the listening process. communicator.BeginListeningAsync(); // Notify listeners of a newly connected client. ClientConnected?.Invoke(); }
private void CreateConnection() { var fserver = new FServer(ServerAddress); fserver.Name = "server" + m_serverCounter; var currentId = GetID(); servers[currentId] = fserver; fserver.Connected += (s, e) => { // create new pipes ondemand CreateConnection(); // require tag fserver.RequestTag(); ClientConnected?.Invoke(currentId, fserver); }; fserver.Disconnected += (s, e) => { ClientDisconnected?.Invoke(currentId, fserver); servers.Remove(currentId); }; fserver.Initialize(); }
private void C_ConnectionError(object sender, EventArgs e) { try { ConnectedClient c = sender as ConnectedClient; if (currentInputClient == c) { SwitchLocalInput(); } try { inputMan.RemoveClientHotkey(c.ClientGuid); } catch (InvalidOperationException ex) { ISLogger.Write("Could not remove hotkey for client {0}: {1}", c.ClientName, ex.Message); } ISLogger.Write("{0} disconnected: Connection error", c.ClientName); clientMan.RemoveClient(c); ClientDisconnected?.Invoke(this, new ClientDisconnectedArgs(CreateClientInfo(c, true), "Connection error")); c.Dispose(); }catch (Exception ex) { ISLogger.Write($"Error occurred while cleaning up client: {ex.Message}"); } }
internal void NotifyClientDisconnected(TcpClient Client) { if (null != ClientDisconnected) { ClientDisconnected.Invoke(this, Client); } }
public void OnClientDisconnected(string clientId) { var client = GetClientById(clientId); _clients.Remove(client); ClientDisconnected?.Invoke(client); }
public void Connect(string ipaddress, string spreadsheetName) { _spreadsheetName = spreadsheetName; var client = new ReactiveClient(ipaddress, 2112); Protocol = new StringChannel(client); Protocol.Receiver.Subscribe(ReceiveMessage); client.Disconnected += ClientOnDisconnected; client.Connected += ClientOnConnected; //Lock this object so that client cannot send a message while receiving one. lock (this) { try { client.ConnectAsync().Wait(); } catch { MessageBox.Show("Could not connect to server! Check that the server is running and that you typed the ip correctly.", "Disconnect", MessageBoxButtons.OK, MessageBoxIcon.Information); ClientDisconnected?.Invoke(); } } }
/// <summary> /// Close a certain client /// </summary> /// <param name="id"></param> public void Close(int id) { var state = GetClient(id); if (state == null) { RaiseErrorThrown(new Exception("Client does not exist.")); } try { if (state?.Listener != null) { state.Listener.Shutdown(SocketShutdown.Both); state.Listener.Close(); } } catch (SocketException se) { throw new Exception(se.ToString()); } finally { lock (ConnectedClients) { var client = GetClient(id); ConnectedClients.Remove(id); ClientDisconnected?.Invoke(client); } } }
/// <summary> /// From PipeClient https://www.codeproject.com/Articles/1179195/Full-Duplex-Asynchronous-Read-Write-with-Named-Pip /// </summary> /// <returns></returns> private ServerPipe CreateServer(string Pipename) { int serverIdx = serverPipes.Count; ServerPipe serverPipe = new ServerPipe(Pipename, p => p.StartMessageReaderAsync()); serverPipes.Add(serverPipe); serverPipe.DataReceived += (sndr, args) => { //Console.WriteLine($"{args.String}"); ServerPipe sender = sndr as ServerPipe; OnMessageReceived(sender, args.Data); }; serverPipe.Connected += (sndr, args) => { ClientConnected?.Invoke(this, new EventArgs()); CreateServer(_Pipename); }; serverPipe.Disconnect += (sndr, args) => { ClientDisconnected?.Invoke(this, new EventArgs()); ServerPipe sender = sndr as ServerPipe; serverPipes.Remove(sender); }; return(serverPipe); }
/// <summary> /// Ping client to indicate disconnected users /// </summary> /// <param name="state"></param> private void PingClient(object state) { lock (_connectedUsers) { List <string> disconnectedUsers = new List <string>(); foreach (KeyValuePair <string, TcpClient> kp in _connectedUsers) { if (!kp.Value.Connected) { disconnectedUsers.Add(kp.Key); } } foreach (string disconnectedUser in disconnectedUsers) { _connectedUsers.Remove(disconnectedUser); _context.Post(p => ClientDisconnected? .Invoke(this, new DisconnectedEventHandlerArgs(null, disconnectedUser)), null); } foreach (TcpClient connectedUsersValue in _connectedUsers.Values) { foreach (string disconnectedUser in disconnectedUsers) { new UserDisconnectPacket(connectedUsersValue.GetStream(), disconnectedUser).Send(); } } } }
/// <summary> /// Waits for new events from another thread and then processes the event queue when messages /// are available. This serves to run all message events on a single thread instead of the multiple threads /// that ASP.NET uses for handling requests. /// </summary> private void ProcessNetworkEvents() { while (true) { // Wait until a new message is received. eventTrigger.WaitOne(); // Dequeue all received messages and execute the appropriate event. while (!eventQueue.IsEmpty) { if (eventQueue.TryDequeue(out var item)) { switch (item.Type) { case IncomingMessageType.Connect: ClientConnected?.Invoke(item.Connection); break; case IncomingMessageType.Disconnect: ClientDisconnected?.Invoke(item.Connection); break; case IncomingMessageType.Data: MessageReceived?.Invoke(item.Connection, item.Message); break; default: throw new ArgumentOutOfRangeException(); } } } } }
public void Kick(int actorNumber) { if (State == ServerState.Debug) { return; } if (State != ServerState.Started) { throw new InvalidOperationException("Cannot kick player: Server not running"); } for (var i = 0; i < _connections.Length; i++) { NetworkConnection connection = _connections[i]; if (connection.InternalId != actorNumber) { continue; } Debug.Log($"Kicking client {actorNumber}"); ClientDisconnected?.Invoke(actorNumber); connection.Disconnect(_serverDriver); _connections.RemoveAtSwapBack(i); return; } Debug.LogWarning($"Tried to kick client {actorNumber}, but did not find respective connection."); }
private protected void InvokeClientDisconnect(T arg0, DisconnectReason reason) { bool lockTaken = false; bool removed; try { _clientsLock.Enter(ref lockTaken); removed = _clients.Remove(arg0); } finally { if (lockTaken) { _clientsLock.Exit(false); } } if (removed) { OnClientDisconnected(arg0, reason); ClientDisconnected?.Invoke(arg0, reason); } OnAfterClientDisconnect(arg0); }
protected override void OnDisconnect(Interlocutor interlocutor) { if (interlocutor == Interlocutor.Client) { ClientDisconnected?.Invoke(); } }
public void Run(int port) { _listener.ConnectionRequestEvent += request => { request.AcceptIfKey(_clientKey); }; _listener.PeerConnectedEvent += peer => { var param = FuncCreateParamOnConnect(peer); _peers.Add(param); netId2Peer.Add(peer.Id, param); ClientConnected?.Invoke(peer); }; _listener.NetworkReceiveEvent += (peer, reader, method) => { OnDataReceived(peer, reader.GetRemainingBytes()); }; _listener.PeerDisconnectedEvent += (peer, info) => { var param = netId2Peer[peer.Id]; FuncRemoveParamOnDisconnect?.Invoke(peer, param); _peers.Remove(param); netId2Peer.Remove(peer.Id); ClientDisconnected?.Invoke(peer); }; _server.Start(port); }
public ServerWorld(ServerOptions options) : base(options, new ServerWorldCreator(options)) { Options = options ?? throw new ArgumentNullException(nameof(options)); void OnWorldCreated() { NetCodeHookSystem hookSystem = World.GetHookSystem() ?? throw new InvalidOperationException(HookSystemDoesNotExistError); hookSystem.RegisterHook <ListeningEvent>(e => { ListenSuccess?.Invoke(); }); hookSystem.RegisterHook <ListenFailedEvent>(e => { ListenFailed?.Invoke(); }); hookSystem.RegisterHook <DisconnectingEvent>(e => { Closed?.Invoke(); }); hookSystem.RegisterHook <ClientConnectedEvent>(e => { ClientConnected?.Invoke(((ClientConnectedEvent)e).ConnectionEntity); }); hookSystem.RegisterHook <ClientDisconnectedEvent>(e => { ClientDisconnected?.Invoke(((ClientDisconnectedEvent)e).NetworkId); }); } WorldCreated += OnWorldCreated; if (WorldCreator.WorldIsCreated) { OnWorldCreated(); } }
private void Listen() { ThreadPool.QueueUserWorkItem(_ => { while (_isListening) { var session = new WebSocketSession(_tcpListener.AcceptTcpClient()); session.HandshakeCompleted += (__, ___) => { Console.WriteLine($"{session.Id}| Handshake Valid."); Clients.Add(session); }; session.Disconnected += (__, ___) => { Console.WriteLine($"{session.Id}| Disconnected."); Clients.Remove(session); ClientDisconnected?.Invoke(this, session); session.Dispose(); }; Console.WriteLine($"{session.Id}| Connected."); ClientConnected?.Invoke(this, session); session.Start(); } _tcpListener.Stop(); }); }
public async Task StartReceive() { while (WebSocket.State == WebSocketState.Open) { IsActive = true; try { var message = await GetMessage(); if (message == null) { IsActive = false; ClientDisconnected?.Invoke(this, "Socket Disconnected"); } else { MessageReceived?.Invoke(this, message); } } catch (Exception ex) { LogEngine.Error(ex); IsActive = false; ClientDisconnected?.Invoke(this, "Socket Disconnected"); break; } } }
/// <summary> /// From PipeClient https://www.codeproject.com/Articles/1179195/Full-Duplex-Asynchronous-Read-Write-with-Named-Pip /// </summary> /// <returns></returns> private void CreateServer(string Pipename) { int serverIdx = serverPipes.Count; ServerPipe serverPipe = new ServerPipe(Pipename, p => p.StartMessageReaderAsync()); serverPipes.Add(serverPipe); serverPipe.DataReceived += (sndr, args) => { //Console.WriteLine($"{args.String}"); ServerPipe sender = sndr as ServerPipe; OnMessageReceived(sender, args.Data); }; serverPipe.Connected += (sndr, args) => { ClientConnected?.Invoke(this, new EventArgs()); CreateServer(_Pipename); }; serverPipe.Disconnect += (sndr, args) => { ServerPipe sender = sndr as ServerPipe; bool bPipeRemoved = serverPipes.Remove(sender); if (!bPipeRemoved) { throw new Exception("Pipe not found, rare case "); } else { ClientDisconnected?.Invoke(this, new EventArgs()); } }; }