public bool TCP_ConnectToServer(IPAddress serverIP) { if (status == TCP_Status.TCP_Disconnected) { TcpClient client = new TcpClient(AddressFamily.InterNetwork); //Try to connect to server var result = client.BeginConnect(serverIP, TCPPort, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2)); //Connection failed if (!success) { return(false); } //Connection build client.EndConnect(result); NET_TcpConnection connection = new NET_TcpConnection(client); connection.Connected(); connectionToServer = connection; status = TCP_Status.TCP_Connected; return(true); } else { return(false); } }
//---------------------------------------------------------------------------------------------// //Private functions: //---------------------------------------------------------------------------------------------// private void TCP_MainThread() { while (serverStatus != TCP_Status.TCP_Shutdown) { while (serverStatus == TCP_Status.TCP_Running) { //Connect to pending connections if (clientCount < 3) { int emptySlot = -1; if (connections[0] == null) { emptySlot = 0; } else if (connections[1] == null) { emptySlot = 1; } else if (connections[2] == null) { emptySlot = 2; } if (this.server.Pending() && blockNewClients == false) { //Build welcome message for new player NET_Messages.NET_Message_Welcome welcomeMessage = new NET_Messages.NET_Message_Welcome(DateTime.Now); NET_DataPack pack = new NET_DataPack(); pack.SetData("YourPlayerID", emptySlot + 2); welcomeMessage.SetData(pack.SerializeData()); //Build new connection to player TcpClient client = server.AcceptTcpClient(); connections[emptySlot] = new NET_TcpConnection(client); connections[emptySlot].Connected(); //Enqueue welcome message connections[emptySlot].TCP_EnqueueMessage(welcomeMessage); clientCount++; } } //Delete disconnected clients for (int x = 0; x < 3; x++) { if (connections[x] != null) { if (connections[x].GetState() == "TCPC_DeleteMe") { connections[x] = null; clientCount--; } } } Thread.Sleep(20); } //Delete disconnected clients for (int x = 0; x < 3; x++) { if (connections[x] != null) { if (connections[x].GetState() == "TCPC_DeleteMe") { connections[x] = null; clientCount--; } } } Thread.Sleep(10); } server.Stop(); //Game is closing! --> Exit thread }