private void AcceptTcpClientCallback(IAsyncResult ar)
        {
            TcpClient tcpClient;

            try {
                tcpClient = Listener.EndAcceptTcpClient(ar);
            } catch (ObjectDisposedException) {
                // The AcceptTcpClient method didn't finish, as the server was shut down.
                // Therefore, we can simply cancel execution of the callback method.
                return;
            }
            var buffer = new byte[tcpClient.ReceiveBufferSize];
            var client = new NetLibServerInternalClient(tcpClient, buffer);

            lock (_clients) {
                _clients.Add(client.ClientId, client);
                if (OnClientConnected != null)
                {
                    OnClientConnected(client.ClientId);
                }
            }
            var stream = client.NetworkStream;

            try {
                stream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client);
            } catch (ObjectDisposedException) {
                HandleDisconnect(client.ClientId);
                return;
            }
            Listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
        }
Example #2
0
        private void AcceptTcpClientCallback(IAsyncResult ar)
        {
            TcpClient tcpClient;
            try {
                tcpClient = Listener.EndAcceptTcpClient(ar);
            } catch (ObjectDisposedException) {
                // The AcceptTcpClient method didn't finish, as the server was shut down.
                // Therefore, we can simply cancel execution of the callback method.
                return;
            }
            var buffer = new byte[tcpClient.ReceiveBufferSize];
            var client = new NetLibServerInternalClient(tcpClient, buffer);

            lock (_clients) {
                _clients.Add(client.ClientId, client);
                if (OnClientConnected != null)
                    OnClientConnected(client.ClientId);
            }
            var stream = client.NetworkStream;
            try {
                stream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client);
            } catch (ObjectDisposedException) {
                HandleDisconnect(client.ClientId);
                return;
            }
            Listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
        }