在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());
}
}
}