C # UDP Multicast disconnects after a few seconds
I have a networking code that connects to a multicast address but disconnects after a few seconds. Can anyone understand what is 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 that it is connected, but wait a second or two and it is disconnected. Am I binding to the wrong ports or something? It seems like every online tutorial does it differently.
source to share
Since you are using UDP, you cannot "connect" to a remote target. The Connectionless Connect method does not connect as such, but acts as a filter on which packets it accepts packets from.
When you say that in a few seconds you will be disconnected, how do you define it? If you are checking the connected status on a socket you are doing the wrong thing. Instead, you should simply start receiving, and the only way to tell the remote socket may have dropped is if you receive a packet with byte 0 or receive an ICMP response from it.
source to share