高手请进,关于Socket 接受多播数据包的问题?
最近用C#中的Socket进行通讯编码。
但是发现在用Socket进行接受组播的时候,因为组播地址不是本地的127.0.0.1所以无法绑定。接受不料组播数据包。
代码如下:
IPEndPoint ipEndPoint = new IPEndPoint(System.Net.IPAddress.Parse(multiIPAddress), mutilUdpPort);
udpReceiveMutilVideoSocket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
udpReceiveMutilVideoSocket.Bind(ipEndPoint);
在Bind的时候,告诉我说,远程主机地址无法绑定。
我也想过用UdpClient,但是UdpClient没有延时设置,如果万一给组播地址发送组播数据包的机器挂了,我这个UdpClient不是一直在那里等待接受数据包吗?这样下来,程序就down在那里啦!
哪位用过用Socket进行接受组播数据包的,指点下啊,谢谢!本人学习C#不到10天啊,大家帮帮忙啊,项目紧急啊,必须尽快解决啦!没有办法啦!
------解决方案--------------------using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPReceiver
{
public delegate void OnReceiveEventHandler(string xmlPack);
/// <summary>
/// MultiCast 的摘要说明。
/// </summary>
public class MultiCast
{
private string addr;
private int port;
private UdpClient subscriber;
private bool bShutDown = true;
private Thread thReceive;
/// <summary>
/// 数据到达事件
/// </summary>
public event OnReceiveEventHandler OnReceive;
/// <summary>
/// 构造
/// </summary>
/// <param name= "multiCastIP "> 组播IP </param>
/// <param name= "udpPort "> 端口 </param>
public MultiCast(string multiCastIP,int udpPort)
{
addr = multiCastIP;
port = udpPort;
OnReceive += new OnReceiveEventHandler(MultiCast_OnReceive);
}
/// <summary>
/// 启动监听
/// </summary>
public void Startup()
{
if (!bShutDown)
return;
subscriber = new UdpClient(port);
IPAddress ipMultiCast = IPAddress.Parse(addr);
try
{
subscriber.JoinMulticastGroup(ipMultiCast);
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show( "无法加入到多播组[ " + addr + "]\n\n " + ex.ToString());
return;
}
//抛出监听线程
bShutDown = false;
thReceive = new Thread(new ThreadStart(Receive));
thReceive.Start();
}
/// <summary>
/// 关闭监听
/// </summary>
public void ShutDown()
{
bShutDown = true;
thReceive.Join(500);
try
{
thReceive.Abort();
}
catch
{
}
subscriber.Close();
subscriber = null;
}
private void MultiCast_OnReceive(string xmlPack)