【问题标题】:How to avoid specifying byte array length when waiting for an input using TCP and sockets使用 TCP 和套接字等待输入时如何避免指定字节数组长度
【发布时间】:2019-06-09 20:40:51
【问题描述】:

问题:
我正在制作一个小应用程序,其中运行时有一个登录页面,要求用户输入用户名和密码。输入这些信息后,信息会使用套接字通过 TCP 发送到服务器。但是,根据我在网上找到的信息,为此,您需要指定字节长度以接收信息(请参见下面的代码)。问题是,当我指定长度时,字符串的其余部分变为 \0\0\0 ,直到所有字节槽都被填满,这会在稍后的过程中引起问题。

我尝试了什么:
我尝试从字符串中删除部分“\0\0\0..”,但由于程序一直未能找到字符“\”而失败。如果我为此使用正确的协议或方法,我不会,但欢迎任何建议。

NetworkStream stream = client.GetStream(); //Gets input stream
            byte[] receivedBuffer = new byte[100]; 
            stream.Read(receivedBuffer, 0, receivedBuffer.Length);
            string msg = Encoding.ASCII.GetString(receivedBuffer,0,receivedBuffer.Length); //translates msg

            if(msg.Contains("|")) //if the msg contains "|" = log-in
                {
                bool cr1 = false;
                bool cr2 = false;
                string[] cre = msg.Split("|");

                if(cre[0] == "admin") //the whole checking system will be made properly and I know this is wrong but its for testing
                {
                    cr1 = true;
                }
                if (cre[1] == "pass")
                {
                    cr2 = true;
                }

                if (cr1 == true && cr2 == true)
                {
                    string answer = "True";
                    Tosend(answer); //Sends response to client
                }
                else
                {
                    string answer = "False";
                    Tosend(answer);
                }
                }

发送东西的类:
静态无效发送(字符串消息)
{
字符串 ip3 = "本地主机";
TcpClient 客户端 = new TcpClient(ip3, 8081);
int bc = Encoding.ASCII.GetByteCount(msg);
字节[] sd = 新字节[bc];
sd = 编码.ASCII.GetBytes(msg);
NetworkStream st = client.GetStream();
st.Write(sd, 0, sd.Length);
st.Close();
客户端.Close();
}

示例
我得到了什么:
输入:user|pass => to bytes => Sends bytes => Bytes received => Bytes translate => msg = user|pass\0\0\0\0\0\0\0\0...
期望:
输入:user|pass => to bytes => 从客户端发送字节 => 服务器接收到的字节 => 翻译的字节 => msg = user|pass

【问题讨论】:

  • 提示:根据文档使用 Read 的 RETURN 值。数组/长度指定可以读取的最大值 - 并且可以读取更少。读入超过实际读取的字节数的数组在技术上是一种缓冲区溢出形式(尽管不是针对不同的对象本身)。

标签: c# .net


【解决方案1】:

NetworkStream.Read 将返回读取的字节数。您可以使用它来仅提取实际数据。

int receivedBytes = stream.Read(receivedBuffer, 0, receivedBuffer.Length);
string msg = Encoding.ASCII.GetString(receivedBuffer,0,receivedBytes);

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多