I have been trying for so long now to understand UDP sockets in C#, but I just can't seem to grasp it.
I have recently created an application that requires the use of a UDP server and client, and so I found some examples online and they worked fine. I implemented them into my application via copy and paste... I was amazed when it gave me different results.
I have googled around a bit to find that most peoples problems occur with their router or firewalls, which I thought could not be the case because the examples worked fine on this computer before moving them to the other application...

I am quite clueless now whats going on. I decided to fire up a packet sniffer to see where packets where going, because they are sent... just not received...
The results came back that from source address "0.0.0.0:0" a packet was sent to destination address ":0" (yes, no IP at all...

).
I have of course coded in the IP and port I WISH to use, and previously when I was using a TCP system that worked fine using the port and IP addresses.
This is the code I use to connect to the server on the client side:
this.InnerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// I have literally no idea what this is meant to do. I have tried a few IP addressed and port 0, all failed to work.
this.TmpRemots = (EndPoint)new IPEndPoint(IPAddress.Any, Port);
this.Server = new IPEndPoint(IPAddress.Parse(IP), Port);
byte[] data = new byte[6] { 0, 0, 0, 0, 0, 0 };
// For some reason, this line fixed the examples.
// Just by sending data before trying to recieve stopped the exception about needing to bind before recieving.
this.InnerSocket.SendTo(data, data.Length, SocketFlags.None, this.Server);
this.RecvThread = new System.Threading.Thread(this.RecvLoop);
this.RecvThread.Start();
And the code for the server to start up:
this.Listener = new IPEndPoint(IPAddress.Any, this._port);
this.sender = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
this.InnerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.InnerSocket.Bind(this.Listener);
this.RecvThread = new System.Threading.Thread(this.RecvLoop);
this.RecvThread.Start();
The receive loops are very similar:
Client Receive loop
try
{
BytesRecieved = this.InnerSocket.ReceiveFrom(RawBuffer, ref TmpRemots);
}
catch (SocketException Exc)
{
switch (Exc.ErrorCode)
{
case 10054:
{
this.Disconnect();
break;
}
}
}
if (BytesRecieved > 0)
{Process();}
And server:
int BytesRecieved = this.InnerSocket.ReceiveFrom(this.RawBuffer, ref this.sender);
if (BytesRecieved > 0)
{Process();}
As I was saying, the client ends up with some funky destination and the server never receives a packet to reply to.
If you have any ideas on what might be causing this, please do let me know. I don't want to have to start these classes from scratch again. UDP is making me sick.