将通过TCP接收的字符串与另一个字符串进行比较

时间:2017-03-14 16:52:14

标签: c# tcp

我从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”进行比较是没有用的,即,该块中没有任何内容被执行。

这种方法的实际错误是什么?我应该做些什么改变来正确地比较字符串?

2 个答案:

答案 0 :(得分:3)

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

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

您需要在代码中添加其他逻辑,以告知一条消息何时停止,另一条消息从接收方开始。这称为Message Framing,为了使程序更新,您需要将该逻辑添加到您的程序中。

答案 1 :(得分:2)

如果您通过WriteLine(与写入)发送文本,您获胜的字符串将是" STOP"而是" STOP \ r \ n",所以你想要Trim()字符串来检查是否相等。

data.Trim() == "STOP"