比较通过NetworkStream发送到/从服务器的值 [英] comparing values sent to/from server by NetworkStream
问题描述
当你知道为什么发送的字符串kamote到服务器和从服务器收到的kamote不一样..
When u know why the sent string "kamote" to server and the string received "kamote" from server are not the same..
客户端
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);
}
}
SERVER
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
Client sent "kamote"
Server received "kamote"
Server sent "kamote"
Client received "kamote"
HandShake()
总是返回false。如何解决这个问题?
HandShake()
always returns false. How can I fix this?
推荐答案
与前面提到的问题一样,你没有跟踪字节数你收到。所以发生的是这样的:
As in the previous question you asked, you're not keeping track of the number of bytes you received. So what's happening is this:
- 在客户端上,您发送字符串kamote。
- 在服务器上,它将该字符串接收到长度为10025字节的缓冲区。
- 服务器然后将整个缓冲区发送回客户端 - 所有10025字节
- 客户端接收全部或部分10025个字节并将其转换为字符串。
- On the client, you send the string "kamote".
- On the server, it receives that string into a buffer that's 10025 bytes long.
- The server then sends the entire buffer back to the client -- all 10025 bytes
- The client receives all or part of those 10025 bytes and converts them to a string.
转换的字符串真的是kamote,后面有一堆0。
The string that gets converted is really "kamote" with a bunch of 0's after it.
你必须使用中的返回值读取
来知道你收到的字节数。
You must use the return value from Read
to know how many bytes you received.
这篇关于比较通过NetworkStream发送到/从服务器的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!