comparing values sent to/from server by NetworkStream

坚强是说给别人听的谎言 提交于 2019-12-11 13:41:59

问题


When u know why the sent string "kamote" to server and the string received "kamote" from server are not the same..

CLIENT

    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();       

Client sent "kamote"
Server received "kamote"
Server sent "kamote"
Client received "kamote"

HandShake() always returns false. How can I fix this?


回答1:


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:

  • 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.

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.




回答2:


Did you try limiting the string length to the actual read bytes like this:

noOfBytes = ns.Read(bytes, 0, ...);
Encoding.ASCII.GetString(bytes, 0, noOfBytes);



回答3:


You are including a lot of 0 characters, since you are including the entire fromServer in getstring. 0s don't print, but they are there. You must tell it the correct number of bytes to decode.



来源:https://stackoverflow.com/questions/6218218/comparing-values-sent-to-from-server-by-networkstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!