示例#1
0
        public void Init()
        {
            if (_initiated)
            {
                return;
            }
            else
            {
                _initiated = true;
            }

            Console.WriteLine("Setting up clientConnection handler");
            // Set up the clientConnection connectionHandler to be able to accept clients on multiple threads
            ClientConnection clientConnection = new ClientConnection();

            // Setup server and start listening for connections
            _server = new TcpListener(_endpoint);
            _server.Start();

            Console.WriteLine($"Listener set up and listening on {_endpoint}");
            Console.WriteLine("Waiting for clients");

            // Loop that keeps accepting users and creates clients within the clientConnection untill the _isAccepting is set to false.
            while (_isAccepting)
            {
                TcpClient client;

                // Wait untill a client connects
                try
                {
                    client = _server.AcceptTcpClient();
                }
                catch (SocketException Exception)
                {
                    Console.WriteLine("Server disconnect when waiting for client.", Exception.Message);
                    return;
                }

                Client temporaryClient = new Client(connectionAmount, client);

                temporaryClient.ReceivedMessageCallback += ReceivedMessage;
                temporaryClient.DisconnectCallback      += ClientDisconnect;

                Console.WriteLine($"Client | {connectionAmount}");

                // Start a new thread with the client and start that thread
                Thread newThread = new Thread(() =>
                {
                    clientConnection.Accept(temporaryClient);
                    ClientConnected?.Invoke(temporaryClient);
                });

                newThread.Start();

                connectionAmount++;

                // Instantly close to keep flow simple
                // _isAccepting = false;
            }
        }
示例#2
0
        /// <summary>
        /// Connected client
        /// </summary>
        /// <param name="client"></param>
        public static void Connected(TcpClient client)
        {
            Interlocked.Increment(ref _sessionId);
            ClientConnection session = new ClientConnection()
            {
                Id = _sessionId
            };

            session.Accept(client);
            session.OnDisconnected += Disconnected;
            _sessions.Add(session.Id, session);
            Log.Info("New client session #{0} is connected.", session.Id);
        }