简体   繁体   English

.NET TCP服务器断开连接

[英].NET TCP Server Dropping Connections

A while back I wrote a little application to implement a TCP Server, but as a newbie to C# .NET I just followed a tutorial. 不久前,我写了一个小应用程序来实现TCP Server,但是作为C#.NET的新手,我只是遵循了一个教程。 The authorization part of it works fine, but due to following the tutorial to closely, after the authorization is made, it drops the connection with tcpClient.Close(); 它的授权部分可以正常工作,但是由于要紧跟本教程,所以在进行授权后,它将与tcpClient.Close()断开连接。

How should I adjust this code to keep listening for more packets? 我应该如何调整此代码以继续侦听更多数据包? I think most servers drop connections after X minutes, but I am still new to this type of thing. 我认为大多数服务器会在X分钟后断开连接,但对于这种情况我仍然是陌生的。

// Starts the TCP RCON Server
public void StartServer()
{
    Console.WriteLine("RCON Server starting on Port: {0}", serverPort);

    this.tcpListener = new TcpListener(IPAddress.Any, serverPort);
    this.listenThread = new Thread(new ThreadStart(ListenForClients));
    this.listenThread.Start();

    Console.WriteLine("RCON Server has been Started.");
}

// Listen for Client Connections
private void ListenForClients()
{
    this.tcpListener.Start();

    while (true)
    {
        // blocks until a client has connected to the server
        TcpClient client = this.tcpListener.AcceptTcpClient();

        // Create a thread for client communication
        Thread clientThread = new Thread(new ParameterizedThreadStart(ReadClientPacket));
        clientThread.Start(client);
    }
}

private void ReadClientPacket(object client)
{
    TcpClient tcpClient = (TcpClient)client;
    NetworkStream clientStream = tcpClient.GetStream();

    bool terminate = false;

    while (!terminate)
    {
        try
        {
            int packetsize;

            // Create a new Packet Object and fill out the data from the incoming TCP Packets
            RCONPacket packet = new RCONPacket();

            using (BinaryReader reader = new BinaryReader(clientStream))
            {
                // First Int32 is Packet Size
                packetsize = reader.ReadInt32();

                packet.RequestId = reader.ReadInt32();
                packet.RconDataReceived = (RCONPacket.RCONDATA_rec)reader.ReadInt32();

                Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, packet.RequestId, packet.RconDataReceived);

                // Read first and second String in the Packet (UTF8 Null Terminated)
                packet.String1 = ReadBytesString(reader);
                packet.String2 = ReadBytesString(reader);

                Console.WriteLine("String1: {0} String2: {1}", packet.String1, packet.String2);

                switch (packet.RconDataReceived)
                {
                    case RCONPacket.RCONDATA_rec.SERVERDATA_AUTH:
                    {
                        if (packet.String1 == "testpass")
                        {
                            Console.WriteLine("Password is Valid");
                            ReplyAuthRequest(packet.RequestId, tcpClient, packet.String1); // Junk Packet
                            ReplyAuthRequest(packet.RequestId, tcpClient, packet.String1);
                        }
                        else
                        {
                            Console.WriteLine("Password is Invalid");
                            ReplyAuthRequest(BAD_PASSWORD, tcpClient, packet.String1); // Junk Packet
                            ReplyAuthRequest(BAD_PASSWORD, tcpClient, packet.String1);

                            terminate = true;
                        }

                        break;
                    }
                    case RCONPacket.RCONDATA_rec.SERVERDATA_EXECCOMMAND:
                    {
                        Console.WriteLine("RCON Command Packet Received");
                        ReplyExecCommand(packet.RequestId, tcpClient);

                        break;
                    }
                    default:
                    {
                        break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            terminate = true;
        }
    }

    tcpClient.Close();
}

If you notice, you have a lot of break statements. 如果您注意到,则有很多break语句。 I am not clear on the entire design of your program, but if you remove those and then add a check for a boolean value in your while loop such as while(!terminated) { .. } , this would ensure that whenever your application tells the program to end or to stop listening, the loop will also be terminated because you would set terminated to true . 我不清楚您的程序的整体设计,但是如果您删除了它们,然后在while循环中添加了对boolean值的检查,例如while(!terminated) { .. } ,这将确保在您的应用程序告诉程序结束或停止侦听时,循环也将终止,因为您将terminated设置为true What you are saying by while(true) is to continue forever until break occurs, which then subsequently breaks out of the while loop and calls .Close() . while(true)是要一直持续下去直到发生break ,然后break退出while循环并调用.Close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM