C# - TcpClient只接收第一个数据包

时间:2016-12-25 17:52:40

标签: c# tcpclient

我正在开发一个c#程序,只是为了获得一些关于TcpClient的知识。因此,该程序从另一个程序接收消息并向其发回OK数据包,确认已建立的连接。

在第一次请求时,它运行良好,发回OK数据包没有任何问题。但在第二次请求时,它根本没有回复。看起来它从未收到客户端的数据包。我可以看到使用数据包嗅探器从客户端发送数据包,但我的服务器没有动作。

它实际上是在控制台上打印所有请求,所以我可以看到是否有某些东西“进入”读取流。如果我关闭服务器或客户端,并重新打开以建立新连接,我会再次收到第一个数据包,但不会收到第二个数据包。

我一直在寻找解决方案,至少一周。许多功能对我来说根本不起作用,我不希望应用程序断开连接并重新连接很多次。

我的服务器代码:

static void Main(string[] args)
{
    int InternalLoop = 0;
    bool Finished = false;
    TcpListener serverSocket = new TcpListener(System.Net.IPAddress.Any, 10000);
    int requestCount = 0;
    TcpClient clientSocket = default(TcpClient);
    serverSocket.Start();
    while (true)
    {
        bool LoopReceive = true;
        bool LoopSend = false;

        Console.WriteLine(" :::: SERVER STARTED OK");
        clientSocket = serverSocket.AcceptTcpClient();
        Console.WriteLine(" :::: CONNECTED TO CLIENT");
        requestCount = 0;
        NetworkStream networkStream = clientSocket.GetStream();

        string Packettosend = "";

        while (LoopReceive == true)
        {
            try
            {
                //Gets the Client Packet
                requestCount = requestCount + 1;
                byte[] bytesFrom = new byte[128];
                networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);

                Packettosend = "ALIVE";
                Console.WriteLine(" ::: SENDING ALIVE PACKET");
                LoopReceive = false;
                LoopSend = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        while (LoopSend == true || InternalLoop < 2)
        {
            try
            {
                InternalLoop += 1;
                if (Packettosend == "ALIVE")
                {
                    Byte[] sendBytes1 = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
                    networkStream.Write(sendBytes1, 0, sendBytes1.Length);
                    networkStream.Flush();

                    LoopReceive = true;
                    LoopSend = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您没有收到第二个数据包的原因是这一行:

clientSocket = serverSocket.AcceptTcpClient();

此调用等待 new 客户端连接到服务器的侦听器套接字。

将此行移到外部循环之外,只接受一个客户端,并在循环中仅使用该单个clientSocket

(我想添加详细信息,但我在路上并且很难在手机上输入所有内容......)