我对此感到困惑...收到的数据前面有什么垃圾字符......每次都有相同的字符集。我试过这个和其他例子......同样的事情。
等待连接... 等待连接...... 从套接字读取32个字节。 数据:??▼?? ??↑??“??☺??♥??♥ASDF :32 向客户端发送了32个字节。
我只是加载并运行此示例... http://msdn.microsoft.com/en-us/library/fx6588te.aspx
答案 0 :(得分: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编码的文本,这是服务器所期望的。