0

你好我从这里得到这个代码来接收多播地址上的数据

 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 行)。
我想要的是接收器显示或保存我的数据,但继续收听更多的数据包。

什么是这样做的好方法?

4

1 回答 1

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());
}
于 2012-11-01T11:50:08.160 回答