繁体   English   中英

如果条件为假时发生的语句(System.Net)

[英]if statement occuring while condition is false (System.Net)

我是新来的,所以如果这篇文章的格式很糟糕,我很抱歉。

所以我遇到的问题...

I am making a Tcp Based messaging app similar to Discord, Teamspeak etc. As you can see below, I have a function that returns a byte[] which is pulled from the network stream. 我还有一个 if/else 语句,以确保 function 不会尝试从未连接的 stream 中提取数据,因此我有一个布尔(已连接)来确定连接的 Z9ED39E2EA931586B5734A985A69。 此布尔值已正确更新以匹配连接状态。 起初我认为这可能是问题,但我通过调试发现它不是。


private byte[] RecieveData(TcpClient server)
        {
            byte[] data = new byte[1024];
            if (connected)
            {
6th line ->     server.GetStream().Read(data, 0, data.Length);
                return data;
            }
            else
            {
                return null;
            }
        }

调试图(由于某种原因无法添加图片)

我的问题是,为什么第 6 行代码 (server.GetStream().Read(data, 0, data.Length);) 在 if 条件为假时运行。 如果您需要我的任何东西(图片、代码等),请询问。 任何帮助将不胜感激。 谢谢!

最小可重现示例

客户:按执行顺序

private void ServerDisconnect(TcpClient server, byte[] data) //Called from a button
    {
        connected = false;
        Server = null;
        Disconnect(server);
    }

public void Disconnect(TcpClient server)// Checks for a connection, if there is, send DISCON request to server, if not dont
    {
        if (server.Connected) SendMessage(server, DISCON, currentUser);
        connected = false;
        server.Close();
    }

private void SendMessage(TcpClient server, byte code, User user)// Uses AddMessageCode method to specify what type of request the message is.
    {
        NetworkStream stream = server.GetStream();
        byte[] data = AddMessageCode(code, ObjectToByteArray(user));//Uses a simple Binary converter to serialize a class.
        stream.Write(data, 0, data.Length);//Sends request to server
    }

private byte[] AddMessageCode(byte code, byte[] data)// Adds the byte code to the start of the data array.
    {
        byte[] newData = new byte[data.Length + 1];
        newData[0] = code;
        Array.Copy(data, 0, newData, 1, data.Length);
        return newData;
    }

理论上,下面的方法应该不会导致错误。 但确实如此。

private byte[] RecieveData(TcpClient server)
    {
        byte[] data = new byte[1024];
        if (server.Connected)
        {
            server.GetStream().Read(data, 0, data.Length);
            return data;
        }
        else
        {
            return null;
        }
    }

如果这还不够清楚。 我道歉。

链接到源代码

在这个特定的例子中,if 语句已经在条件为真的情况下执行了。 我不明白的部分是stream.Read()方法等到收到数据才能继续。

如果这没有意义,这是@mjwills 的一个类比,

if 语句是房子,门是条件。 如果您在门打开时进入房屋(条件为真),无论门是否打开(条件为真或假),您都在房屋中( if 语句中的代码正在执行)。 在这种情况下,里面的代码不会很快完成,它会等待来自 stream 的数据。

感谢 stackoverflow 社区在问题发布后的 10 分钟内帮助我理解这一点!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM