1

我用 C# 编写了一个小套接字应用程序,它在每次启动时检查我的程序的当前版本,现在在我的测试程序中一切正常,我可以从服务器发送字符串,它将正确显示在客户端,但是当我尝试使用带有该字符串的 if 语句时,它就不起作用了。例子:

    public void rcv(NetworkStream ns, TcpClient clientSocket)
    {
        on = false;
    //sending some random string so the server will respond
       Byte[] sendBytes = Encoding.ASCII.GetBytes("bla");
        ns.Write(sendBytes, 0, sendBytes.Length);
    //receiving server response 
        byte[] bytes = new byte[clientSocket.ReceiveBufferSize];
        int bytesread = clientSocket.ReceiveBufferSize;
        ns.Read(bytes, 0, bytesread);
    //received response, now encoding it to a string from a byte array
        string returndata =Encoding.ASCII.GetString(bytes);
        ver = Convert.ToString(returndata);
        //MessageBox.Show("ver\n" + ver);
        //MessageBox.Show("return\n" + returndata);
        on = true;
        if (ver== "2.0.1")
        {
            MessageBox.Show("iahsd");
        }
    }

如您所见,服务器发送的即时测试字符串是“2.0.1”确实正确显示在标签、消息框和我放入测试的文本框上。但是类末尾的 if 分支不接受它并跳过它,如果我放入 else 语句,它会跳到那个。

我已经尝试了我和我的朋友能想到的一切,尝试更改编码,发送不同的字符串等。

客户端的完整代码:http: //pastebin.com/bQPghvAH

4

2 回答 2

1

在您的代码中编译的“2.0.1”存储为 Unicode。 http://msdn.microsoft.com/en-us/library/362314fe(v=vs.110).aspx

您将来自服务器的值视为 ASCII 编码文本,然后将其与 Unicode 字符串进行比较。

观察:

    static void Main(string[] args)
    {
        string a = "hello";
        byte[] b = UnicodeEncoding.Unicode.GetBytes(a);
        string c = ASCIIEncoding.ASCII.GetString(b);

        Console.WriteLine(a == c);
    }

解决方案是使用 String.Compare...

Console.WriteLine(String.Compare(a,c)==0);
于 2012-11-16T13:25:09.180 回答
1

Stream.Read(...)返回读取的字节数。您需要使用此值来确定字符串的结束位置,方法是使用Encoding.GetString(Byte[] bytes, Int32 index, Int32 count)重载。

Byte[] buffer = ...;
var bytesRead = stream.Read(buffer, 0, buffer.Length);
var returnedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
于 2012-11-16T13:34:33.063 回答