Ejemplo n.º 1
0
        private void HandleClientConnected(ClientConnected message)
        {
            if (!_connectedClients.ContainsKey(message.ClientId))
            {
                _connectedClients.Add(message.ClientId, new ConnectedUserData()
                {
                    Name = message.Name,
                    ClientGuid = message.ClientId,
                    LastActivity = DateTime.UtcNow,
                    ClientActorPath = message.Client.Path
                });

                message.Client.Tell(new ConnectResponse(_connectedClients.Values.ToList()), Self);
            }
        }
Ejemplo n.º 2
0
        private void WaitForClientConnections()
        {
            while (_running)
            {
                try
                {
                    var clientSocket = _listenerSocket.AcceptSocket();
                    if (clientSocket.Connected)
                    {
                        // Upon connection, remote agent must immediately send its Id as identification.
                        // Guid is sent as a raw byte array, without any preceding length specified.
                        byte[] bytes = ReadBytes(clientSocket, GUID_BUFFER_SIZE);

                        Guid id = new Guid(bytes);
                        ClientConnected?.Invoke(clientSocket, id);
                    }
                }
                catch
                {
                    // Two possibilities:
                    //   1. We were trying to stop the socket
                    //   2. The connection was dropped due to some external event
                    // In either case, we stop the socket and wait a while
                    _listenerSocket.Stop();

                    // If we were trying to stop, that's all
                    if (!_running)
                    {
                        return;
                    }

                    // Otherwise, wait and try to restart it. An exception here is simply logged
                    Thread.Sleep(500);
                    try
                    {
                        _listenerSocket.Start();
                    }
                    catch (Exception exception)
                    {
                        log.Error($"Unable to restart listener socket: {exception}");
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// ClientConnected is a callback that gets called when the server accepts a client connection from the async BeginAccept method.
        /// </summary>
        /// <param name="ar"></param>
        /// <remarks></remarks>
        public void ClientAccepted(IAsyncResult ar)
        {
            // get the async state object from the async BeginAccept method, which contains the server's listening socket
            Socket mServerSocket = ar.AsyncState.CastType <Socket>();
            // call EndAccept which will connect the client and give us the the client socket
            Socket mClientSocket = null;

            try
            {
                mClientSocket = mServerSocket.EndAccept(ar);
            }
            catch //(ObjectDisposedException ex)
            {
                // if we get an ObjectDisposedException it that means the server socket terminated while this async method was still active
                return;
            }
            // instruct the client to begin receiving data
            //In the very first connection we have to send the id to the client
            ulong genID = 1;

            //Give id in a range...
            bool b = routingTable.Keys.FindFirstMissingNumberFromSequence(out genID, new MinMax <ulong>(1, (ulong)routingTable.Count));

            myLogger.Log("Adding #{0} client to routing table!", genID); //Esto ni parece funcionar bien

            SocketContainer co = new SocketContainer(genID, mClientSocket);

            if (!routingTable.ContainsKey(genID))
            {
                routingTable.Add(genID, co);
            }
            else
            {
                Console.WriteLine("Overlapping ID error!");
            }

            //We don't have a way to know if there was a problem in the transmission ???
            SendToClient(SocketManager.ReturnClientIDAfterAccept(genID), routingTable[genID]);
            ClientConnected?.Invoke(routingTable[genID]);

            routingTable[genID].Socket.BeginReceive(routingTable[genID].rState.Buffer, 0, gBufferSize, SocketFlags.None, new AsyncCallback(ClientMessageReceived), routingTable[genID]); //ClientMessageReceived
            // begin accepting another client connection
            mServerSocket.BeginAccept(new AsyncCallback(ClientAccepted), mServerSocket);
        }
Ejemplo n.º 4
0
        private void AcceptCallback(IAsyncResult ar)
        {
            Socket socket;

            try
            {
                socket = ServerSocket.EndAccept(ar);
            }
            catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
            {
                return;
            }

            ClientSockets.Add(socket);
            socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
            // Console.WriteLine("Client connected, waiting for request...");
            ClientConnected?.Invoke();
            ServerSocket.BeginAccept(AcceptCallback, null);
        }
Ejemplo n.º 5
0
 private void WaitForConnectionCallBack(IAsyncResult result)
 {
     if (_isStopping)
     {
         return;
     }
     lock (_locker)
     {
         if (_isStopping)
         {
             return;
         }
         _serverStream.EndWaitForConnection(result);
         ClientConnected?.Invoke(this, ID);
         var response = GetResponse();
         SendResponse(response);
         ClientDisconnected?.Invoke(this, ID);
     }
 }
        private async Task HandleMessage(WebSocket websocket)
        {
            try
            {
                if (ClientConnected != null)
                {
                    ClientConnected.Invoke(websocket);
                }

                while (websocket.IsConnected)
                {
                    string message = await websocket
                                     .ReadStringAsync(CancellationToken.None)
                                     .ConfigureAwait(false);

                    //Console.WriteLine("Websocket: Got message.");
                    if (message != null &&
                        MessageReceived != null)
                    {
                        MessageReceived.Invoke(websocket, message);
                    }
                }

                if (ClientDisconnected != null)
                {
                    ClientDisconnected.Invoke(websocket);
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex);
                if (ErrorThrown != null)
                {
                    ErrorThrown.Invoke(websocket, ex);
                }
            }

            finally
            {
                websocket.Dispose();
            }
        }
        //async will create code behing
        public async void StartListeningFoIncommingConnection(IPAddress ipAddress = null, int port = 23000)
        {
            //sanity check
            if (ipAddress == null)
            {
                ipAddress = IPAddress.Any;
            }

            if (port <= 0)
            {
                port = 23000;
            }

            myIP   = ipAddress;
            myPort = port;

            Debug.WriteLine(string.Format("IP Adress: {0} - Port: {1}", myIP.ToString(), myPort.ToString()));

            myTCPListener = new TcpListener(myIP, myPort);
            try
            {
                myTCPListener.Start();

                isRunning = true;
                while (isRunning)
                {
                    var returnedByAccept = await myTCPListener.AcceptTcpClientAsync(); //returns a TCPClient (helper class)

                    myClients.Add(returnedByAccept);

                    Debug.WriteLine(string.Format("Client connected successfully, number of clients connected {0} - "
                                                  , myClients.Count, returnedByAccept.Client.RemoteEndPoint));

                    ClientConnected?.Invoke(this, new ClientConnectedEventArgs(returnedByAccept.Client.RemoteEndPoint.ToString()));

                    TakeCareOfTcpClient(returnedByAccept);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
Ejemplo n.º 8
0
        public void Listen()
        {
            TcpListener ServerSocket = new TcpListener(IP, Port);

            ServerSocket.Start();

            while (true)
            {
                TcpClient tcpClient = ServerSocket.AcceptTcpClient();

                var client = new Client(tcpClient);

                Clients.Add(client);

                ClientConnected?.Invoke(this, new ConnectionEventArgs(client));

                new Thread(() => StartRecieve(client)).Start();
            }
        }
Ejemplo n.º 9
0
        //Dedicate one thread to incoming connections
        private void ThreadListener()
        {
            try
            {
                ServerStarted?.Invoke();

                while (true)
                {
                    Socket hNewConnection = m_hListener.Accept(); //il thread sta in attesa per una connessione in ingresso

                    //T deve ricevere il socket, 2 modi: 1) T implementa un interfaccia interna, 2) creiamo un allocatore per T
                    T hConnHandler = new T();
                    hConnHandler.Socket = hNewConnection;
                    hConnHandler.CreateBuffer(m_iBufferSize);

                    lock (m_hConnections)
                    {
                        hConnHandler.Id    = s_iCounter;
                        hConnHandler.Owner = this;

                        m_hConnections.Add(hConnHandler.Id, hConnHandler);
                        s_iCounter++;                        
                    }

                    hConnHandler.BeginReceive(); //connection now active, let the user code handle requests and resposes

                    try
                    {
                        ClientConnected?.Invoke(hConnHandler);
                    }
                    catch (Exception)
                    {
                        //Se qualcuno nell'implementazione dell'evento fa danni... a noi non ci interessa
                    }
                }
            }
            catch (Exception)
            {
                //se siamo qui è xche abbiamo chiamato stop quindi possiamo interrompere il ciclo
                ServerStopped?.Invoke();                
            }
        }
Ejemplo n.º 10
0
        private void PublisherChannelAccepted(object sender, ClientAcceptedEventArgs args)
        {
            ClientConnected?.Invoke(this, args);

            var channel = args.Channel;

            Task.Factory.StartNew(() =>
            {
                while (args.Channel.IsOpened)
                {
                    try
                    {
                        var topicMessage = channel.Receive(_stringMessageSerializer.Value);
                        if (topicMessage == null)
                        {
                            return;
                        }

                        var contentMessage = channel.Receive();
                        if (contentMessage == null)
                        {
                            return;
                        }

                        channel.Send(new StringMessage(PublicationConfirmString), _stringMessageSerializer.Value);

                        _publisher.Broadcast(topicMessage.ToString(), contentMessage);
                    }
                    catch (Exception ex) when(ex is DataTransferException || ex is IOException)
                    {
                        CommunicationFailed?.Invoke(this, new ExceptionEventArgs(ex));

                        if (channel.IsOpened)
                        {
                            channel.Close();
                        }

                        return;
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
Ejemplo n.º 11
0
    public void Listen(int port)
    {
        if (_listening)
        {
            throw new Exception("Already listening!");
        }
        _listening = true;

        var server = new TcpListener(IPAddress.Any, port);

        server.Start();

        Console.WriteLine("WS Server - UP");

        ThreadPool.QueueUserWorkItem(_ =>
        {
            while (_listening)
            {
                var session = new WebSocketSession(server.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();
            }

            server.Stop();
        });
    }
Ejemplo n.º 12
0
        private void TcpListener_ClientConnected(object sender, ClientConnectedArgs e)
        {
            ConnectedClient c = new ConnectedClient(e.ClientSocket, e.ClientName, e.ClientId);

            try
            {
                clientMan.AddClient(c);
            }
            catch (ClientManager.DuplicateNameException)
            {
                ISLogger.Write("Declining client {0}: Name already in use", c.ClientName);
                c.SendMessage(InputshareLib.Net.Messages.MessageType.ClientDuplicateName);
                c.Dispose();
                return;
            }
            catch (ClientManager.DuplicateGuidException)
            {
                ISLogger.Write("Declining client {0}: Guid already in use", c.ClientName);
                c.SendMessage(InputshareLib.Net.Messages.MessageType.ClientDuplicateGuid);
                c.Dispose();
                return;
            }
            catch (ClientManager.MaxClientsReachedException)
            {
                ISLogger.Write("Declining client {0}: Max clients reached", c.ClientName);
                c.SendMessage(InputshareLib.Net.Messages.MessageType.ClientLimitReached);
                c.Dispose();
                return;
            }
            ApplyClientConfig(c.ClientGuid);
            c.SendMessage(InputshareLib.Net.Messages.MessageType.ServerOK);
            ISLogger.Write("{0} connected from {1}", e.ClientName, e.ClientSocket.RemoteEndPoint);
            ConnectedClientInfo info = CreateClientInfo(c, true);

            ClientConnected?.Invoke(this, CreateClientInfo(c, true));



            c.ClipboardTextCopied += C_ClipboardTextCopied;
            c.ConnectionError     += C_ConnectionError;
            c.ClientEdgeHit       += OnAnyEdgeHit;
        }
Ejemplo n.º 13
0
        private void StartServer(IPAddress pIPAddress, int pPort, X509Certificate2 pCert = null)
        {
            Log.Info("Starting WebSocket server");
            Log.Info($"Listening on {pIPAddress.ToString()}:{pPort}");

            _objWebSocket           = new WebSocketServer(pIPAddress, pPort, (pCert != null));
            _objWebSocket.WaitTime  = new TimeSpan(0, 0, ConnectionTimeoutSeconds);
            _objWebSocket.Log.Level = WebSocketSharp.LogLevel.Fatal;

            if (pCert != null)
            {
                Log.Info("Setting up a secure connection...");
                _objWebSocket.SslConfiguration.ServerCertificate = pCert;
            }
            _objWebSocket.AddWebSocketService("/", delegate(WebsocketClientWrapper pClient) {
                ClientConnected?.Invoke(this, pClient);
            });
            _objWebSocket.KeepClean = true;
            _objWebSocket.Start();
        }
Ejemplo n.º 14
0
 public void AwaitConnection()
 {
     socket.Bind(ipe);
     socket.Listen(5); // socket waiting for 5 connections in line
     running = true;
     while (running)
     {
         try
         {
             Socket        clientRequest = socket.Accept();
             ClientHandler newClient     = new ClientHandler(clientRequest);
             ClientList.Add(newClient);
             ClientConnected?.Invoke(this, newClient);
             newClient.ReceivedMsg += NewClient_ReceivedMsg;
         }
         catch (Exception e)
         {
         }
     }
 }
Ejemplo n.º 15
0
        // Endless Start listening loop
        private async void StartListening()
        {
            Socket.Listen(10);
            // Loop theoretically infinetly
            while (true)
            {
                var client = await Socket.AcceptAsync().ConfigureAwait(false); // Block until accept

                var endpoint = client.RemoteEndPoint as IPEndPoint;            // Get remote endpoint
                Sockets.Add(endpoint, client);                                 // Add client to dictionary

                StartReading(client);                                          // Start listening for data
                KeepAlive(client);                                             // Keep client alive and ping

                ClientConnected?.Invoke(endpoint);                             // call event
            }
            // Listen again after client connected

            // ReSharper disable once FunctionNeverReturns
        }
Ejemplo n.º 16
0
        public MqttServer(IEnumerable <IMqttServerAdapter> adapters, IMqttNetChildLogger logger)
        {
            if (adapters == null)
            {
                throw new ArgumentNullException(nameof(adapters));
            }
            _adapters = adapters.ToList();

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            _logger = logger.CreateChildLogger(nameof(MqttServer));

            _eventDispatcher.ClientConnected            += (s, e) => ClientConnected?.Invoke(s, e);
            _eventDispatcher.ClientDisconnected         += (s, e) => ClientDisconnected?.Invoke(s, e);
            _eventDispatcher.ClientSubscribedTopic      += (s, e) => ClientSubscribedTopic?.Invoke(s, e);
            _eventDispatcher.ClientUnsubscribedTopic    += (s, e) => ClientUnsubscribedTopic?.Invoke(s, e);
            _eventDispatcher.ApplicationMessageReceived += (s, e) => ApplicationMessageReceived?.Invoke(s, e);
        }
Ejemplo n.º 17
0
        private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);

                    var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer());
                    ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
                }
                catch (Exception exception)
                {
                    MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at default endpoint.");

                    //excessive CPU consumed if in endless loop of socket errors
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 18
0
        private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null);

                    var sslStream = new SslStream(new NetworkStream(clientSocket));
                    await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false);

                    var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream), new DefaultMqttV311PacketSerializer());
                    ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
                }
                catch (Exception exception)
                {
                    MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while acceping connection at TLS endpoint.");
                }
            }
        }
Ejemplo n.º 19
0
        protected virtual void CheckRecieved(Object o)
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);

            if (Globals.FDAStatus != Globals.AppState.Normal)
            {
                goto ResetTimer;
            }
            // check for pending connections
            if (_server.Pending())
            {
                Client client = new Client(_server.AcceptTcpClient() /*, _serverCertificate*/);
                if (client.Connected)
                {
                    client.Disconnected += ClientDisconnectedHandler;

                    _clients.Add(client.ID, client);

                    //Globals.SystemManager.LogApplicationEvent(this, "", "Accepted TCP connection from " + client.Address);
                    ClientConnected?.Invoke(this, new ClientEventArgs(client.ID, client.Address));
                }
            }

            // check for received messages
            foreach (Client client in _clients.Values)
            {
                byte[] received;
                while (client.ReceivedQueue.Count > 0)
                {
                    lock (client.ReceivedQueue)
                    {
                        received = client.ReceivedQueue.Dequeue();
                    }

                    DataAvailable?.Invoke(this, new TCPCommandEventArgs(client.ID, client.Address, received));
                }
            }

ResetTimer:
            _timer.Change(_tickRate, Timeout.Infinite);
        }
Ejemplo n.º 20
0
    private void EnqueueIncomingPacket(INetWrapper netWrapper, uint binaryAddress, PacketId packetId, byte[] data, uint?ping)
    {
        if (!this.clients[netWrapper].ContainsKey(binaryAddress))
        {
            var client = this.clientCreationMethod?.Invoke(binaryAddress, netWrapper) ??
                         new Client(binaryAddress, netWrapper);
            AssociateElement(client.Player);

            this.clients[netWrapper][binaryAddress] = client;
            ClientConnected?.Invoke(client);
        }

        if (ping != null)
        {
            this.clients[netWrapper][binaryAddress].Ping = ping.Value;
        }

        this.packetReducer.EnqueuePacket(this.clients[netWrapper][binaryAddress], packetId, data);

        if (
            packetId == PacketId.PACKET_ID_PLAYER_QUIT ||
            packetId == PacketId.PACKET_ID_PLAYER_TIMEOUT ||
            packetId == PacketId.PACKET_ID_PLAYER_NO_SOCKET
            )
        {
            if (this.clients[netWrapper].ContainsKey(binaryAddress))
            {
                var client = this.clients[netWrapper][binaryAddress];
                client.IsConnected = false;
                var quitReason = packetId switch
                {
                    PacketId.PACKET_ID_PLAYER_QUIT => QuitReason.Quit,
                    PacketId.PACKET_ID_PLAYER_TIMEOUT => QuitReason.Timeout,
                    PacketId.PACKET_ID_PLAYER_NO_SOCKET => QuitReason.Timeout,
                    _ => throw new NotImplementedException()
                };
                client.Player.TriggerDisconnected(quitReason);
                this.clients[netWrapper].Remove(binaryAddress);
            }
        }
    }
Ejemplo n.º 21
0
        private async Task WaitForClientAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    if (_pipe.IsConnected)
                    {
                        return;
                    }
                    await _pipe.WaitForConnectionAsync(cancellationToken);

                    var negotiationMessage = (Message)_formatter.Deserialize(_pipe);
                    if (negotiationMessage.Type != MessageType.Negotiation)
                    {
                        _logger.LogTrace("Negotiation message not correct type");
                        SendMessage(Message.CreateError(
                                        _configuration.ClientInfo,
                                        negotiationMessage.SenderInfo,
                                        negotiationMessage.Id,
                                        new NegotiationException(
                                            $"Expected a negotiation message but got: {Enum.GetName(typeof(MessageType), negotiationMessage.Type)}"),
                                        null));
                        Regenerate();
                    }
                    else
                    {
                        _logger.LogTrace("Received negotiation: {@negotiation}", negotiationMessage);
                        ConnectedClient = negotiationMessage.SenderInfo;
                        SendMessage(Message.CreateNegotiation(_configuration.ClientInfo));
                        ClientConnected?.Invoke(this, new ClientConnectedEventArgs(ConnectedClient));
                        return;
                    }
                }
                catch (IOException e)
                {
                    _logger.LogWarning(e, "IO Exception when waiting for client");
                    Regenerate();
                }
            }
        }
Ejemplo n.º 22
0
        protected override void ListeningLoop()
        {
            try
            {
                while (true)
                {
                    Socket newClient = _Socket.Accept();

                    ClientHandlerSocket newChs = new ClientHandlerSocket(this, newClient);

                    _ConnectedClientSockets.Add(newChs);

                    ClientConnected.Invoke(newChs);

                    newChs.Start();
                }
            }
            catch (ThreadAbortException)
            {
            }
        }
Ejemplo n.º 23
0
    public override void Start()
    {
        _server = new WebSocketServer(IPAddress.Any, _serverPort, true);
        var path = System.IO.Path.Combine(Application.streamingAssetsPath, "Certs", "localhost.pfx.bin");

        byte[] content = UnityEngine.Windows.File.ReadAllBytes(path);
        _server.SslConfiguration.ServerCertificate          = new System.Security.Cryptography.X509Certificates.X509Certificate2(content);
        _server.SslConfiguration.CheckCertificateRevocation = false;
        _server.AddWebSocketService <WebRtcSession>("/", newSession =>
        {
            Debug.Log("Incoming connection ...");
            if (_session != null)
            {
                Debug.Log("Another session is running. Ignore request");
                return;
            }
            newSession.MessageReceived += MessageReceived;
            newSession.SocketOpen      += () =>
            {
                Debug.Log("Socket open!");
                ClientConnected?.Invoke();
            };
            newSession.SocketClosed += () =>
            {
                Debug.Log("Socket closed!");
                _session = null;
            };
            newSession.ConnectionError += (errorMessage) =>
            {
                Debug.LogWarning(errorMessage);
                newSession.Context.WebSocket.Close();
                // OnClose is only triggered when the connection was established before
                // unsetting _session in case SocketClosed was not fired.
                _session = null;
            };
            _session = newSession;
        });
        _server.Start();
        Debug.Log($"Waiting for browser web socket connection to {_server.Address}:{_server.Port}...");
    }
Ejemplo n.º 24
0
        public void LaunchProcess()
        {
            bool processIsLaunched = true;

            try
            {
                while (processIsLaunched)
                {
                    string clientRequest = service.GetData();

                    if (String.IsNullOrEmpty(clientRequest))
                    {
                        break;
                    }

                    if (clientFirstRequest)
                    {
                        clientName = clientRequest.Substring(0, clientRequest.IndexOf(':'));
                        ClientConnected?.Invoke(clientName);
                        clientFirstRequest = false;
                    }

                    Console.WriteLine(DateTime.Now.ToShortTimeString() + " " + clientRequest);

                    clientRequest = clientRequest.Substring(clientRequest.IndexOf(':') + 1).Trim();

                    service.SendData(clientRequest);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                ClientDisconnected(clientName);
                service.Disconnect();
            }
        }
Ejemplo n.º 25
0
        public void StartServer()
        {
            _listener = new TcpListener(_ip, _port);
            _listener.Start();
            Console.WriteLine("Started TCP Server on " + _ip + ":" + _port);

            Task waitForClients = new Task(new Action(() =>
            {
                while (true)
                {
                    var clientTask = _listener.AcceptTcpClientAsync();
                    if (clientTask.Result != null)
                    {
                        TcpClient client = clientTask.Result;
                        ClientConnected.Invoke(this, client);
                        Console.WriteLine(client.Client.RemoteEndPoint + " connected.");
                    }
                }
            }));

            waitForClients.Start();
        }
Ejemplo n.º 26
0
 private void ServerListenHandler()
 {
     WriteLine("Server Listening on " + this.aEndPoint);
     while (this.pListener.Active)
     {
         try {
             TcpClient cli = this.pListener.AcceptTcpClient();
             ClientConnected?.Invoke((IPEndPoint)cli.Client.RemoteEndPoint);
             WriteLine("Client[" + cli.Client.RemoteEndPoint.ToString() + "] connected!");
             Thread cliComm = new Thread(new ParameterizedThreadStart(ClientCommunicationHandler));
             ConnectedClients.Add(cli);
             cliComm.Start(cli);
         } catch (SocketException sockEx) {
             if (sockEx.ErrorCode != 10004) //WSACancelBlockingCall
             {
                 WriteLine(sockEx);
             }
         }catch (ObjectDisposedException disposeEx) {
             WriteLine(disposeEx);
         }
     }
 }
        public virtual void Add(IOnlineClient client)
        {
            lock (SyncObj)
            {
                var userWasAlreadyOnline = false;
                var context = client.ToClientContextOrNull();

                if (context != null)
                {
                    userWasAlreadyOnline = this.IsOnline(context);
                }

                Store.Add(client);

                ClientConnected?.Invoke(this, new OnlineClientEventArgs(client));

                if (context != null && !userWasAlreadyOnline)
                {
                    UserConnected?.Invoke(this, new OnlineUserEventArgs(context, client));
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 添加Client
        /// </summary>
        /// <param name="client"></param>
        public void Add(IOnlineClient client)
        {
            lock (_syncObj)
            {
                var userWasAlreadyOnline = false;
                var user = client.ToUserIdentifierOrNull();

                if (user != null)
                {
                    userWasAlreadyOnline = IsUserOnline(user);
                }

                AddClientToRedisStore(client);

                ClientConnected.InvokeSafely(this, new OnlineClientEventArgs(client));

                if (user != null && !userWasAlreadyOnline)
                {
                    UserConnected.InvokeSafely(this, new OnlineUserEventArgs(user, client));
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Constantly listens for new clients until _serverRunning is false (server is shutting down)
        /// </summary>
        protected virtual async void _newClientLoop()
        {
            while (_serverRunning)
            {
                _server.Start();
                try
                {
                    TcpClient newTcpClient = await _server.AcceptTcpClientAsync();

                    _handleNewClient(newTcpClient);

                    ClientConnected?.Invoke(this);
                }
                catch (ObjectDisposedException) //Because the listener was stopped which threw this
                {
                    if (_serverRunning)         //If this exception happens while the server is running, we have problems
                    {
                        throw;
                    }
                }//*/
            }
        }
        public void Add(IOnlineClient client)
        {
            lock (_syncObj)
            {
                var userWasAlreadyOnline = false;
                var user = client.ToUserIdentifier();

                if (user != null)
                {
                    userWasAlreadyOnline = this.IsOnline(user);
                }

                _clients[client.ConnectionId] = client;

                ClientConnected.InvokeSafely(this, new OnlineClientEventArgs(client));

                if (user != null && !userWasAlreadyOnline)
                {
                    UserConnected.InvokeSafely(this, new OnlineUserEventArgs(user, client));
                }
            }
        }
Ejemplo n.º 31
0
        private void InvokeClientConnected(T arg0)
        {
            if (CreateServerClient(arg0, out TServerClient serverClient))
            {
                bool lockTaken = false;
                try
                {
                    _clientsLock.Enter(ref lockTaken);
                    _clients.Add(arg0, serverClient);
                }
                finally
                {
                    if (lockTaken)
                    {
                        _clientsLock.Exit(false);
                    }
                }

                OnClientConnected(arg0);
                ClientConnected?.Invoke(arg0);
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Add a TCP listener to the specified port
        /// </summary>
        /// <param name="port">Port number to listen on</param>
        /// <param name="connectCallback">Callback function that is called when a new client connects</param>
        public static void AddTcpListener(UInt16 port, ClientConnected connectCallback)
        {
            if (tcpListeners.ContainsKey(port) == true)
            {
                throw new ArgumentException("Port is already subscribed to", "port");
            }

            tcpListeners.Add(port, connectCallback);
        }