关于C#的UDP编程。

wsmall1 2004-11-16 04:53:20
我知道一个网关机的IP以及发送数据报的端口,请问我还需要那些条件才能编写客户端来接收他们发送出来的数据。他们发送数据的方式是广播方式的。

我下面写了一段程序,但是运行的时候会死掉。我分步检查,发现运行到
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
这句的时候,程序就死了,请高手指点。。

我的程序图如下:
UdpClient receivingUdpClient = new UdpClient();
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("192.17.101.8"), 2000);
try
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

string returnData = Encoding.ASCII.GetString(receiveBytes);

MessageBox.Show("This is the message you received " +
returnData.ToString());
MessageBox.Show("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message.ToString());
}
...全文
354 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
cometsky 2004-12-08
  • 打赏
  • 举报
回复
你忘记了最重要的一句:
UdpClient.JoinMulticastGroup(GroupAddress);


private static readonly IPAddress GroupAddress = IPAddress.Parse("224.168.100.2");
private const int GroupPort = 11000;
listener.JoinMulticastGroup(GroupAddress);
listener.Connect(groupEP);
...
while (!done)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive( ref groupEP);

Console.WriteLine("Received broadcast from {0} :\n {1}\n",
groupEP.ToString(),
Encoding.ASCII.GetString(bytes,0,bytes.Length));
}


lucbesson 2004-12-08
  • 打赏
  • 举报
回复
建议楼主使用线程 !
lucbesson 2004-12-08
  • 打赏
  • 举报
回复
UdpClient receivingUdpClient = new UdpClient();
没有指定端口
----------------------

IPEndPoint RemoteIpEndPoint ;
RemoteIpEndPoint=null ;

Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);


wanglei9802 2004-12-06
  • 打赏
  • 举报
回复
基本上没有什么问题
zxilu 2004-12-06
  • 打赏
  • 举报
回复
不是死掉,是等待数据包吧。
wsmall1 2004-11-17
  • 打赏
  • 举报
回复
有人知道么?
_jfeng 2004-11-16
  • 打赏
  • 举报
回复
学习 ,,,up

110,546

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧