private void ClientOnTryConnect(IAsyncResult res) { try { TcpListener Server = res.AsyncState as TcpListener; TcpClient NewHost = Server.EndAcceptTcpClient(res); string key = ((IPEndPoint)NewHost.Client.RemoteEndPoint).ToString(); if (!ClientsPool.ContainsKey(key)) { Thread Handler = new Thread(new ParameterizedThreadStart(MaintainConnection)); ClientsPool.Add(key, NewHost); Handler.Start(NewHost); } Server.BeginAcceptTcpClient(new AsyncCallback(ClientOnTryConnect), Server); } catch (ObjectDisposedException) { return; } }
public void Connect(IPEndPoint Opponent) { //will be called when player 2 wants to connect to the host //method will add player to pool, and elicit select player TcpClient NewPlayer = new TcpClient(LocalPoint); try { NewPlayer.Connect(Opponent); Mode = false; ClientsPool.Add(Opponent.ToString(), NewPlayer); EnemyPoint = Opponent; Thread Handler = new Thread(new ParameterizedThreadStart(MaintainConnection)); Handler.Start(NewPlayer); SendMessage(NewPlayer.GetStream(), MessageCode.PlayRequest); } catch (SocketException err) { throw new FailedToConnectException("Невозможно подключиться к серверу"); } }