如何将字节转换为布尔值

时间:2012-10-02 06:03:10

标签: c#

我想将一个字节转换为布尔值。这是代码:

String text = textBox1.Text;
UdpClient udpc = new UdpClient(text,8899);
IPEndPoint ep = null;

while (true)
{
    MessageBox.Show("Name: ");
    string name = "Connected";
    if (name == "") break;

    byte[] sdata = Encoding.ASCII.GetBytes(name);
    udpc.Send(sdata, sdata.Length);

    if (udpc.Receive(ref ep)=null)
    {
      //  MessageBox.Show("Host not found");
    }
    else
    {        
        byte[] rdata = udpc.Receive(ref ep);
        string job = Encoding.ASCII.GetString(rdata);
        MessageBox.Show(job);
    }
}

我想将这行代码转换为布尔值:

  udpc.Receive(ref ep);

2 个答案:

答案 0 :(得分:3)

您根本不想仅仅将结果与null进行比较......这样您就会丢失实际数据,然后再次调用Receive,从而有效地跳过数据包。

您应该使用:

byte[] data = udpc.Receive(ref ep);
if (data == null)
{
    // Whatever
}
else
{
    MessageBox.Show(Encoding.ASCII.GetBytes(data));
}

另请注意,此代码已损坏:

string name = "Connected";
if (name == "") break;

当您将name设置为"Connected"时,{{1}}怎么可能是空字符串?

答案 1 :(得分:0)

UdpClient自然阻塞,直到收到字节为止。

这意味着您根本不应该获取数据,假设您正在寻找表明您是否已收到数据的方法,那么一旦您移过udpc.Recieve,您应该返回true。 / p>

我还会考虑更改代码,因为= null语句会有一些编译问题,因为这不会转换为可编译的代码表达式。

当您尝试从UDP客户端读取消耗已发送数据时,if else语句也存在问题。

就个人而言,我会选择UDP套接字,但为了让你滚动,我会将代码更改为:

String text = textBox1.Text;
UdpClient udpc = new UdpClient(text,8899);
IPEndPoint ep = null;

while (true)
{
    MessageBox.Show("Name: ");
    string name = "Connected";
    if (name == "") break; //This will never happen because you have already set the value
    byte[] sdata = Encoding.ASCII.GetBytes(name);
    int dataSent = 0;
    try
    {
        dataSent = udpc.Send(sdata, sdata.Length);
    }
    catch(Exception e)
    {
        dataSent = 0;
        //There is an exception. Probably the host is wrong
    }
    if (dataSent > 0)
    {
        try
        {
            byte[] rdata = udpc.Receive(ref ep);
            if(rdata!=null && rdata.Length > 0)
            {
                string job = Encoding.ASCII.GetString(rdata);
                MessageBox.Show(job)
                //True here as we managed to recieve without going to the catch statement
                //and we actually have data in the byte[]
            }
            else
            {
                MessageBox.Show("We did not recieve any data");
                //False here, because the array was empty.
            }
        }
        catch(Exception udpe)
        {
            //False here as we had a socket exception or timed out
            MessageBox.Show(udpe.ToString());
        }
    }
}