//Method is used to accept incoming connection
        public void AcceptCallback(IAsyncResult result)
        {
            Connection connection = new Connection();

            lock (locker) // establish only one connection at time
            {
                try
                {
                    //we try to make a connection
                    connection           = new Connection();
                    connection.tcpClient = TCPListener.EndAcceptTcpClient(result); // Ending accepting the connection
                    // Adding client to connections that are already established
                    Connections.Add(connection);

                    //Handshake based on WebSocket protocol
                    confirmConnectionByHandshake(connection);
                }
                catch (ObjectDisposedException e)
                {
                    Console.WriteLine(e.ToString()); // if anything went wrong
                }
            }
            try
            {
                //print that client has connected
                Console.WriteLine("Client connected: " +
                                  ((IPEndPoint)connection.tcpClient.Client.RemoteEndPoint).Address +
                                  ":" + ((IPEndPoint)connection.tcpClient.Client.RemoteEndPoint).Port);
            }
            catch (Exception)
            {
                ///...
            }

            try
            {
                // start of the async data reading that are being send via TCP protocol
                connection.tcpClient.GetStream().BeginRead(connection.buffer, 0, connection.buffer.Length,
                                                           new AsyncCallback(ReadCallBack), connection);
            }
            catch (Exception)
            {
                try
                {
                    // If connection is lost print information
                    Console.WriteLine("Connection lost: " + ((IPEndPoint)connection.tcpClient.
                                                             Client.RemoteEndPoint).Address + ":" +
                                      ((IPEndPoint)connection.tcpClient.Client.RemoteEndPoint).Port);

                    //Delete information about the connection
                    disconnect(((IPEndPoint)connection.tcpClient.Client.RemoteEndPoint));
                }
                catch (Exception)
                {
                    ///...
                }
            }
            // Start async method that waits for accepting another connection
            TCPListener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), null);
        }
예제 #2
0
 private static void TCPBeginAcceptClient()
 {
     TCPListener.BeginAcceptTcpClient(new AsyncCallback(TCPConnectAsyncCallback), null);
 }