c#ip multicast接收并保存多个数据包

时间:2012-11-01 11:39:55

标签: c# sockets network-programming udp multicast

您好我从here获取此代码以接收有关多播地址的数据

 Socket sock = new Socket(AddressFamily.InterNetwork,
            SocketType.Dgram, ProtocolType.Udp);
 Console.WriteLine("Ready to receive…");
 IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
 EndPoint ep = (EndPoint)iep;
 sock.Bind(iep);
 sock.SetSocketOption(SocketOptionLevel.IP, 
            SocketOptionName.AddMembership, 
            new MulticastOption(IPAddress.Parse("224.100.0.1")));
 byte[] data = new byte[1024];
 int recv = sock.ReceiveFrom(data, ref ep);
 string stringData = Encoding.ASCII.GetString(data, 0, recv);
 Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
 sock.Close();

现在,当我收到一个数据包,然后sock.ReceiveFrom被触发,但之后接收器关闭(即使我删除了sock.Close行)。 我想要的是接收器显示或保存数据但继续侦听更多数据包。

这样做的好方法是什么?

1 个答案:

答案 0 :(得分:1)

您必须编写某种循环代码或使用异步方法BeginReceive / EndReceive。 一旦你的本地sock变量超出范围,它就可能被gc收集并被处理掉。

byte[] data = new byte[1024];

while (true) {
    // this blocks until some bytes are received
    int recv = sock.ReceiveFrom(data, ref ep);
    string stringData = Encoding.ASCII.GetString(data, 0, recv);
    Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
}