I was told that UDP was connectionless meaning that you could not be sure if the packages would reach the destination.
Why when doing:
var dataToSend = new byte[]{1};
UdpClient client = new UdpClient();
client.Send(dataToSend,1,"192.168.0.45", 1234);
the variable LocalEndpoint initializes:
Correct me if I am wrong. I believe that the variable LocalEndPoint was initialized by the router. The reason why I believe that is because every time the server (192.168.0.45) receives data and then replies, I see that data is being send through the port 62446 on the reply.
So my question is if I am using the udp protocol why am I getting a response from the router? If I am getting a response from the router then that is not UDP or perhaps I have a wrong understanding of udp. I dont think the port number get's randomly picked. If I have had configure the router to do port forwarding on port 62446 to some other computer then my program will not have had worked.
here is the client code:
string ipOfServer = "192.168.0.45";
int portServerIsListeningOn = 1234;
// send data to server
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint sending_end_point = new IPEndPoint(IPAddress.Parse(ipOfServer), portServerIsListeningOn);
sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
// after I send data localendpoint gets initialized! and the server always respond through that port!
// get info
var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
// now wait for server to send data back
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
byte[] buffer = new byte[1024];
sending_socket.Receive(buffer); // <----- keeps waiting in here :(
here is the server code:
// wait for client to send data
UdpClient listener = new UdpClient(11000);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);
byte[] receive_byte_array = listener.Receive(ref groupEP);
listener.Connect(groupEP);
// reply
byte[] dataToSend = new byte[] { 1, 2, 3, 4, 5 };
listener.Send(dataToSend, dataToSend.Length);