2012-10-02 87 views
-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); 
+2

? – TheZ

+0

你的意思是说,你想要真正或错误的价值返回主机被发现或没有? – Derek

+1

使用比较运算符'==' – Jcl

回答

3

你不想只是比较空的结果都...这样,您将丢失实际数据,然后再次拨打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"

0

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

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

我也会考虑改变一下代码,因为你将会对= null语句有一些编译问题,因为这不会转化为可编译的代码表达式。

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

个人而言,我会选择一个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()); 
     } 
    } 
}