关于基于UDP协议的编程,请大家来看看。
我做了一个基于UDP协议程序,一个广播式的发送消息,一个接送消息,利用UDP协议的不用相互之间产生连接的特点。
发送消息端(在此之列出关键方法):
private static void Send(String message)
{
UdpClient sender = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort);
try
{
byte[] bytes = Encoding.ASCII.GetBytes(message);
i = sender.Send(bytes, bytes.Length, groupEP);
sender.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
发送端运行正常,没有问题,我利用时钟控件控制发送,每5秒发送一次。
调用方式为: Send("Hello");
我的接收端,因为不能和发送端建立连接,所以采用加入广播的方式来接收。接收方法如下:
private static void StartListener()
{
bool done = false;
UdpClient listener = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort);
try
{
listener.JoinMulticastGroup(GroupAddress);
listener.Connect(groupEP);
while (!done)
{
byte [] bytes = listener.Receive(ref groupEP);
}
listener.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
当接收端程序运行到 byte [] bytes = listener.Receive( ref groupEP); 这一句的时候,程序就死掉了,请问是怎么回事?