-2

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

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);
4

2 回答 2

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"

于 2012-10-02T06:11:37.903 回答
0

UdpClient接收到字节之前,它自然是阻塞的。

这意味着您根本不应该获取数据,假设您正在寻找一种方法来指示您是否已收到数据,那么一旦您经过udpc.Recieve,您应该返回 true。

我还会考虑稍微更改代码,因为该= 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());
        }
    }
}
于 2012-10-02T07:46:46.980 回答