【问题标题】:Comparing a string received via TCP against another string将通过 TCP 接收的字符串与另一个字符串进行比较
【发布时间】:2017-03-15 01:08:19
【问题描述】:

我从 MSDN 获得了以下代码:

using System;       
using System.IO;      
using System.Net;
using System.Net.Sockets;
using System.Text;

class MyTcpListener
{
public static void Main()
{
    TcpListener server = null;
    try
    {

        Int32 port = 13000; // Set the TcpListener on port 13000.
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");


        server = new TcpListener(localAddr, port); // TcpListener server = new TcpListener(port);
        server.Start(); // Start listening for client requests.

        // Buffer for reading data
        Byte[] bytes = new Byte[256];
        String data = null;

        // Enter the listening loop.
        while (true)
        {
            Console.Write("Waiting for a connection... ");

            // Perform a blocking call to accept requests.
            // You could also user server.AcceptSocket() here.
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Connected!");

            data = null;
            NetworkStream stream = client.GetStream();// Get a stream object for reading and writing

            int i;


            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)  // Loop to receive all the data sent by the client.
            {     
               data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); // Translate data bytes to a ASCII string.
                Console.WriteLine("Received: {0}", data);        
                data = data.ToUpper();// Process the data sent by the client.

                byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                stream.Write(msg, 0, msg.Length); // Send back a response.
                Console.WriteLine("Sent: {0}", data);


                if(data == "STOP")
                {
                    Console.WriteLine("Stop command Received.");
                    Console.ReadKey();
                    Environment.Exit(0);
                }


                Console.WriteLine(data.Length);

            }
            client.Close(); // Shutdown and end connection
        }
    }
    catch (SocketException e)
    {
        Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
        server.Stop();// Stop listening for new clients.
    }

    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
}
}

除了我插入的以下几行:

            if(data == "STOP")
            {
                Console.WriteLine("Stop command Received.");
                Console.ReadKey();
                Environment.Exit(0);
            }

我通过 tcp 客户端发送了一个字符串“STOP”。但是,在服务器中,将接收到的字符串“STOP”与“if 块”中的“STOP”进行比较是没有用的,即,该块中没有任何内容被执行。

这种方法的实际错误是什么?我应该进行哪些更改才能正确比较字符串?

【问题讨论】:

  • 你确实需要learn how to debug small programs,你应该能够使用调试器将代码单步执行到if(data == "STOP") 行,看看是什么导致了问题。

标签: c# tcp


【解决方案1】:

如果Ben's answer 不能解决您的问题,则说明您的代码存在第二个主要问题。

您的代码不能保证您不会在一次读取中获得ST,在下一次读取中不会获得OP。一次发送允许拆分为多次读取,多次发送允许合并为一次读取。因此,当您调用读取函数时,发送Test 然后发送STOP 可能会显示为TestSTOP

您需要在代码中添加额外的逻辑来判断一条消息何时停止,而另一条消息何时在接收端开始。这称为Message Framing,为了使您添加到程序中工作,您需要将该逻辑添加到您的程序中。

【讨论】:

    【解决方案2】:

    如果您通过 WriteLine(相对于 Write)发送文本,您收到的字符串将不是“STOP”而是“STOP\r\n”,因此您需要将字符串 Trim()检查是否相等。

    data.Trim() == "STOP" 
    

    【讨论】:

    • 只是想知道,为什么接收到的字符串会加上\r\n。有没有目的。
    • 否则,对方怎么知道自己收到了整件东西?
    • @programminghorse 这是我在回答中谈到的消息框架。你会一直阅读直到你看到一个 \r\n 然后一旦你点击其中一个,你就会开始处理你的消息,看看消息是否是你所期望的。
    • 发送的代码是在发送的消息末尾附加 \r\n 的代码(可能使用 WriteLine 函数)。这有好有坏,取决于你想做什么。就像@Scott 提到的那样,没有 100% 保证您发送的内容将以相同的顺序收到(例如,“测试”然后“停止”可能会被接收为“测试停止”,具体取决于许多外部因素 [尽管,您很可能会在测试时看到它按预期出现])。所以 \r\n 可以帮助你拆分消息(假设消息本身没有 \r\n )
    • @ BenAbraham ,有时,当我将服务器收到的数据发回给客户端时,我得到的是客户端之前发送的数据,而不是直接发送的数据。这是您之前提到的问题的症状吗?
    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多