首页 > 解决方案 > 使用 TCP 和套接字等待输入时如何避免指定字节数组长度

问题描述

问题:
我正在制作一个小应用程序,运行时它有一个登录页面,要求用户输入用户名和密码。输入这些信息后,信息会使用套接字通过 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);
                }
                }

发送东西的类:
static void Tosend(string msg)
{
string ip3 = "localhost";
TcpClient 客户端 = 新 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();
客户端.关闭();
}

示例
我得到的内容:
输入:用户|通过 => 到字节 => 发送字节 => 接收的字节 => 翻译的字节 => msg = 用户|通过\0\0\0\0\0\0\0\0。 ..
期望:
输入:用户|通过 => 到字节 => 从客户端发送字节 => 服务器接收到的字节 => 字节翻译 => msg = 用户|通过

标签: c#.net

解决方案


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

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

推荐阅读