Beispiel #1
0
        /// <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");
        }
        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);
            }
        }
Beispiel #3
0
        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();
            });
        }
Beispiel #4
0
        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;
                }
            }
        }
        public bool Remove(string connectionId)
        {
            lock (_syncObj)
            {
                var isRemoved   = false;
                var _database   = GetDatabase();
                var clientValue = _database.HashGet(_clientStoreKey, connectionId);
                if (clientValue.IsNullOrEmpty)
                {
                    return(isRemoved);
                }

                _database.HashDelete(_clientStoreKey, connectionId);
                isRemoved = true;

                var client = JsonConvert.DeserializeObject <OnlineClient>(clientValue);

                if (isRemoved)
                {
                    var user = client.ToUserIdentifierOrNull();

                    if (user != null && !IsUserOnline(user))
                    {
                        UserDisconnected.InvokeSafely(this, new OnlineUserEventArgs(user, client));
                    }

                    ClientDisconnected.InvokeSafely(this, new OnlineClientEventArgs(client));
                }

                return(isRemoved);
            }
        }
        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();
                }
            }
        }
Beispiel #7
0
 internal void NotifyClientDisconnected(TcpClient Client)
 {
     if (null != ClientDisconnected)
     {
         ClientDisconnected.Invoke(this, Client);
     }
 }
Beispiel #8
0
        // 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);
        }
Beispiel #9
0
        private void OnClientDisconnected(ITcpProtocolClient client_)
        {
            UnsubscribeFromClientEvents(client_);
            _clientList.Remove(client_);

            ClientDisconnected?.Invoke(this, client_);
        }
Beispiel #10
0
        /// <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);
        }
Beispiel #11
0
        public void OnClientDisconnected(string clientId)
        {
            var client = GetClientById(clientId);

            _clients.Remove(client);
            ClientDisconnected?.Invoke(client);
        }
Beispiel #12
0
        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();
        }
        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);
            }
        }
 protected override void OnDisconnect(Interlocutor interlocutor)
 {
     if (interlocutor == Interlocutor.Client)
     {
         ClientDisconnected?.Invoke();
     }
 }
Beispiel #15
0
 /// <summary>
 /// Fires the ClientDisconnected event.
 /// </summary>
 /// <param name="client">Client that disconnected</param>
 public void FireClientDisconnected(Client client)
 {
     PluginUtils.ProtectedInvoke(() =>
     {
         ClientDisconnected?.Invoke(client);
     }, "ClientDisconnected");
 }
Beispiel #16
0
        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.");
        }
Beispiel #17
0
            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;
            }
Beispiel #18
0
        /// <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();
                        }
                    }
                }
            }
        }
Beispiel #19
0
        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);
        }
        /// <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);
                }
            }
        }
Beispiel #21
0
        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}");
            }
        }
Beispiel #22
0
        //

        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;
                    }
                }
            }
        }
        /// <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();
        }
Beispiel #24
0
        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);
        }
Beispiel #25
0
        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);
        }
Beispiel #26
0
        protected void DisconnectEventHandler(UdpClient client, bool remoteTrigger = false)
        {
            if (serverMode == false)
            {
                if (!socketClosed)
                {
                    socket.Close();
                    socketClosed = true;
                }
                else
                {
                    return;
                }
            }

            if (ClientDisconnected != null)
            {
                Array.ForEach(ClientDisconnected.GetInvocationList(), d => d.DynamicInvoke(this));
            }

            lock (sentReliableDataLock)
            {
                sentReliablePacketInfo.Clear();
            }
        }
        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();
                }
            }
        }
Beispiel #28
0
        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();
            }
        }
Beispiel #29
0
 public void Close()
 {
     ms.Close();
     ms.Dispose();
     tcpClient.Close();
     ClientDisconnected?.Invoke(this);
 }
Beispiel #30
0
        /// <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();
                    }
                }
            }
        }
Beispiel #31
0
 private bool Equals(ClientDisconnected other)
 {
     return Equals(_name, other._name);
 }
Beispiel #32
0
        /// <summary>
        /// Sets handlers for client acceptance and disconnections.
        /// </summary>
        /// <param name="clientAcceptedHandler">Accepted clients are reported by this handler.</param>
        /// <param name="clientDisconnectedHandler">Client disconnection is reported by this handler.</param>
        public void SetClientHandlers(ClientAccepted clientAcceptedHandler, ClientDisconnected clientDisconnectedHandler)
        {
            if (clientAcceptedHandler == null)
                throw new ArgumentNullException("clientAcceptedHandler");

            if (clientDisconnectedHandler == null)
                throw new ArgumentNullException("clientDisconnectedHandler");

            if (_clientAcceptedHandler != null || _clientDisconnectedHandler != null)
                throw new NotSupportedException("Cannot change client handlers.");

            _clientAcceptedHandler = clientAcceptedHandler;
            _clientDisconnectedHandler = clientDisconnectedHandler;
        }
 private void HandleClientDisconnect(ClientDisconnected message)
 {
     if (_connectedClients.ContainsKey(message.ClientId))
         _connectedClients.Remove(message.ClientId);
 }