0

我对此感到有点困惑......接收到的数据前面的垃圾字符是什么......每次都使用相同的字符集。我试过这个和其他例子......同样的事情。

等待连接... 等待连接... 从套接字读取 32 个字节。资料:??▼?? ??↑??'??☺??♥??♥asdf : 32 向客户端发送了 32 个字节。

我只是加载和运行这个例子...... http://msdn.microsoft.com/en-us/library/fx6588te.aspx

4

1 回答 1

0

没有任何垃圾字符;以下是好的:

static void Client(object state)
{
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    using (var client = new TcpClient())
    {
        client.NoDelay = true;
        client.Connect(localEndPoint);
        using (var ns = client.GetStream())
        {
            string data = @"this is 
some random data
with multiple lines
<EOF>"; // <=== server explicitly expects this as a sentinel value

            var buffer = Encoding.ASCII.GetBytes(data);
            ns.Write(buffer, 0, buffer.Length);

            // note: normally I'd use Socket etc; ReadToEnd is
            // ... unreliable on a NetworkStream
            using (var sr = new StreamReader(ns))
            {
                // for this ^^^ to end, it means the server disconnected
                // the socket, which means it got the <EOF> and shutdown
                string s = sr.ReadToEnd();
                Console.WriteLine("From server:");
                Console.WriteLine(s);
            }
        }
    }
}
public static int Main(String[] args) {
    ThreadPool.QueueUserWorkItem(Client);
    // ^^^ client on a different thread to the server
    StartListening();
    return 0;
}

我猜错误出在“客户端”代码中,您没有向我们展示。大概它不是服务器所期望的 ASCII 编码文本。

于 2012-12-03T06:59:19.883 回答