Example #1
0
        // ReSharper restore FunctionNeverReturns

        private static void ListenForNewConnectionThread()
        {
            try
            {
                _tcpListener.Start();
            }
            catch (SocketException ex)
            {
                //todo: this will cause hard crash on the client, need a nicer way for the client to handle errors here
                if (ex.ErrorCode == 10048)
                {
                    throw new Exception("Only one server allowed at a time.");
                }
            }

            while (true)
            {
                TcpClient           client;
                System.Net.EndPoint endPoint;
                //blocks until a client has connected to the server
                try
                {
                    client = _tcpListener.AcceptTcpClient();
                    client.GetStream().WriteTimeout = 30000;
                    endPoint = client.Client.RemoteEndPoint;
                }
                catch
                {
                    WriteToServerConsoleLog("Failed to accept connection");
                    continue;
                }

                try
                {
                    WriteToServerConsoleLog(string.Format("Accepting connection from {0}", endPoint));
                    var connect = new Connect();
                    connect.AcceptNewConnection(client);                     //backdoor constructor because a player does not exist yet

                    var player = new NetworkPlayer(_nextPlayerId, connect.UserName, client)
                    {
                        Coords = new Coords(WorldData.SizeInBlocksX / 2f, 0, WorldData.SizeInBlocksZ / 2f)
                    };
                    player.Coords.Yf = WorldData.Chunks[player.Coords].HeightMap[player.Coords.Xblock % Chunk.CHUNK_SIZE, player.Coords.Zblock % Chunk.CHUNK_SIZE] + 1;                     //start player on block above the surface
                    new Connect(player.Id, player.UserName, player.Coords)
                    {
                        ConnectedPlayer = player, Immediate = true
                    }.Send();
                    _nextPlayerId++;

                    WriteToServerConsoleLog(String.Format("{0} (id {1}, ip {2}) Connected", player.UserName, player.Id, player.IpAddress));
                    var tcpThread = new Thread(() => PlayerThread(player))
                    {
                        IsBackground = true, Name = "PlayerThread"
                    };
                    tcpThread.Start();
                }
                catch (Exception ex)
                {
                    WriteToServerConsoleLog(string.Format("Failed to accept connection from {0}: {1}", endPoint, ex.Message));
                }
            }
            // ReSharper disable FunctionNeverReturns
        }