I Was working with XXXAsync methods and socketeventargs in c# then when testing my console app, data was not being sent (locally- within a pc) and no error was thrown with this code at sender app.
public class Client
{
private static Socket FlashUDP = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private static IPEndPoint send_ipep = new IPEndPoint(IPAddress.Parse("192.168.100.41"), 14086);
private static IPEndPoint rec_ipep = new IPEndPoint(IPAddress.Parse("192.168.100.41"), 14085);
private static SocketAsyncEventArgs Sock_Args = new SocketAsyncEventArgs();
private static SocketAsyncEventArgs Sock_Args2 = new SocketAsyncEventArgs();
private static byte[] dat1 = new byte[10];
//This function is called at main
private static void starter()
{
Sock_Args.RemoteEndPoint = send_ipep;
Sock_Args.Completed += Sock_Args_Completed;
string st = "ping";
byte[] msg = Encoding.ASCII.GetBytes(st);
Sock_Args.SetBuffer(msg, 0, 4);
// FlashUDP.SendTo(msg, rec_ipep);
try
{
FlashUDP.Bind(rec_ipep);
// FlashUDP.Connect(send_ipep);
FlashUDP.SendAsync(Sock_Args);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Sending...");
}
private static void Sock_Args_Completed(object sender, SocketAsyncEventArgs e)
{
Console.WriteLine("sent sucessfully ");
Console.WriteLine("++++++++++++++++++++++++");
}
But this app sent data sucessfully when that connect() code in the try catch block was un-commented. It also sent data when
FlashUDP.SendTo("dat1", send_ipep);
was used insted of
FlashUDP.SendAsync(Sock_Args);
Am i missing something or it is the way udp works? What i had supposed it if
"SentTo()"
works without connection then
"SendAsync()"
also should work without connection. Connecting is not problem for client but it is a problem for server as it have to deal with many clients. plus data are not being sent over when i dont bind() the reciver. Is there any solution for this? Thank You!
According to the SendTo documentation this is expected behaviour:
If you are using a connectionless protocol [addition by me: which UDP is], you do not need to establish a default remote host with the Connect method prior to calling SendTo. You only need to do this if you intend to call the Send method.
The SendAsync documentation (with SendAsync being the async equivalent of Send mentioned earlier) then states:
The SendAsync method will throw an exception if you do not first call Accept, AcceptAsync, BeginAcceptBeginConnect, Connect, or ConnectAsync.
If you want the same behaviour as SendTo you should use SendToAsync:
If you are using a connectionless protocol, you do not need to establish a default remote host with the BeginConnect, Connect, or ConnectAsync method prior to calling SendToAsync. You only need to do this if you intend to call the BeginSend or SendAsync methods.