当你知道为什么发送到服务器的字符串“kamote”和从服务器接收到的字符串“kamote”不一样时..
客户
tcpClient = new TcpClient();
tcpClient.Connect(ServerIP, Port);
connectionState = (HandShake("kamote", tcpClient)) ? "Connected to " + ServerIP.ToString() : "Host unreachable.";
private bool HandShake(String str, TcpClient tcpClient)
{
using (NetworkStream ns = tcpClient.GetStream())
{
byte[] toServer = Encoding.ASCII.GetBytes(str);
ns.Write(toServer,0,toServer.Length);
ns.Flush();
byte[] fromServer = new byte[10025];
ns.Read(fromServer, 0, (int)tcpClient.ReceiveBufferSize);
return Encoding.ASCII.GetString(fromServer).Equals(str);
}
}
服务器
TcpClient tcpClient = new TcpClient();
tcpClient = tcpListener.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
byte[] fromClient = new byte[10025];
ns.Read(fromClient, 0, (int)tcpClient.ReceiveBufferSize);
byte[] toClient = fromClient;
ns.Write(toClient, 0, toClient.Length);
ns.Flush();
客户端发送“kamote”
服务器收到“kamote”
服务器发送“kamote”
客户端收到“kamote”
HandShake()
始终返回 false。我该如何解决这个问题?
最佳答案
正如您在上一个问题中所问的那样,您没有跟踪收到的字节数。所以发生的事情是这样的:
- 在客户端,您发送字符串“kamote”。
- 在服务器上,它将该字符串接收到一个 10025 字节长的缓冲区中。
- 然后服务器将整个缓冲区发送回客户端——所有 10025 字节
- 客户端接收全部或部分这 10025 个字节并将它们转换为字符串。
转换后的字符串实际上是“kamote”,后面有一堆 0。
您必须使用Read
的返回值来了解您收到了多少字节。
关于c# - 比较通过 NetworkStream 发送到服务器/从服务器发送的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218218/