示例#1
0
        private void Listen(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                if (listenWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                TcpListener tcpListener = (TcpListener)e.Argument;

                try
                {
                    for (int i = 0; i < Players.Count; i++)
                    {
                        if (!((TcpClient)Players[i].SocketEndpoint).Connected)
                        {
                            Players.RemoveAt(i--);
                        }
                    }

                    // Create a TCP socket.
                    // If you ran this server on the desktop, you could use
                    // Socket socket = tcpListener.AcceptSocket()
                    // for greater flexibility.
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();

                    if (Connections >= MaxConnections)
                    {
                        lock (writeMutex)
                        {
                            writeBuffer.Clear();
                            ObjectMapper.MapBytes(writeBuffer, "Max Players Reached On Server");

                            staticWriteStream.SetProtocolType(Networking.ProtocolType.TCP);
                            WriteAndClose(tcpClient, staticWriteStream.Prepare(
                                              this, NetworkingStream.IdentifierType.Disconnect, null, writeBuffer));
                        }

                        return;
                    }

                    // TODO:  Set the name
                    string name = string.Empty;

                    NetworkingPlayer player = new NetworkingPlayer(ServerPlayerCounter++, tcpClient.Client.RemoteEndPoint.ToString(), tcpClient, name);

                    lock (Players)
                    {
                        Players.Add(player);
                    }

                    listenWorker.ReportProgress(0, player);
                }
                catch (NetworkException exception)
                {
                    UnityEngine.Debug.LogException(exception);
                    Disconnect();
                }
            }
        }