C# UDP 多播在几秒钟后断开连接
我有一些网络代码连接到多播地址,但几秒钟后断开连接。谁能找出这段代码有什么问题吗?
String Target_IP = "224.1.2.3";
int Target_Port = 31337;
IPEndPoint LocalEP = new IPEndPoint(IPAddress.Any, Target_Port);
IPEndPoint RemoteEP = new IPEndPoint(IPAddress.Parse(Target_IP), Target_Port);
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
//s.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
//s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(LocalEP);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(Target_IP)));
s.Connect(RemoteEP);
// TODO
}
调用 Connect() 函数后,它会报告已连接,但等待一两秒就会断开连接。我是否绑定到了错误的端口或其他什么?每个在线教程似乎都以不同的方式进行。
I have some networking code which connects to a multicast address but disconnects after a few seconds. Can anyone figure out what's wrong with this code?
String Target_IP = "224.1.2.3";
int Target_Port = 31337;
IPEndPoint LocalEP = new IPEndPoint(IPAddress.Any, Target_Port);
IPEndPoint RemoteEP = new IPEndPoint(IPAddress.Parse(Target_IP), Target_Port);
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
//s.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
//s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(LocalEP);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(Target_IP)));
s.Connect(RemoteEP);
// TODO
}
After the Connect() function is called it reports as connected, but wait a second or two and it is disconnected. Am I binding to the wrong ports or something? Every online tutorial seems to do it a different way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您使用的是 UDP,因此您无法“连接”到远程目标。无连接协议上的 Connect 方法不会像这样进行连接,而是充当一个过滤器,用于确定它将接受来自哪些目的地的数据包。
当你说几秒钟后断开连接时,你如何确定这一点?如果您正在检查套接字上的连接状态,那么您就做错了。相反,您应该开始接收,判断远程套接字“可能”已断开的唯一方法是您是否收到 0 字节数据包或从中收到 ICMP 响应。
Since you are using UDP you cannot "connect" to the remote target. The Connect method on connectionless protocols does not connect as such but acts as a filter on what destintations it will accept packets from.
When you say you disconnect after a few seconds how are you determining that? If you are checking th connected status on the socket you are doing the wrong thing. Instead you should just start receiving and the only way to tell that the remote socket "may" have dropped off is if you get a 0 byte packet or you get an ICMP response from it.