如果条件为false时发生if语句(System.Net)

我是新来的,所以如果这篇文章的格式非常糟糕,我深表歉意。

所以我遇到的问题...

我正在制作一个类似于Discord,Teamspeak等的基于Tcp的消息传递应用程序。如下所示,我有一个函数,该函数返回从网络流中提取的byte []。我还有一条if / else语句,以确保该函数不会尝试从未连接的流中提取数据,所以我有一个bool(已连接)来确定连接状态。此布尔已正确更新以匹配连接状态。我本来以为这可能是问题所在,但通过调试发现并非如此。


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

Picture of debugging (cant add images for some reason)

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

最小可复制示例

客户: 按执行顺序

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,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,newData,1,data.Length);
        return newData;
    }

理论上,以下方法不应导致错误。但确实如此。

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

如果仍然不清楚。我道歉。

Link to source code

wewewe22 回答:如果条件为false时发生if语句(System.Net)

在此特定实例中,if语句已在条件为true的情况下执行。我不了解的部分是stream.Read()方法要等到收到数据才能继续。

如果那没有道理,那么这里是@mjwills的类比,

if语句是房屋,门是条件。如果您是在门打开的情况下进入房屋的(条件为真),无论门是否打开(条件为真或假的),您都处于房子( if语句中的代码正在执行)。在这种情况下,内部代码无法快速完成,它等待流中的数据。

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

本文链接:https://www.f2er.com/3129533.html

大家都在问