0

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!

4

1 回答 1

0

根据SendTo 文档,这是预期的行为:

如果您使用的是无连接协议 [我的补充:UDP 是],则无需在调用 SendTo 之前使用 Connect 方法建立默认远程主机。仅当您打算调用 Send 方法时才需要这样做。

SendAsync 文档(其中SendAsync 是前面提到的 Send 的异步等效项)然后指出:

如果您不先调用 Accept、AcceptAsync、BeginAcceptBeginConnect、Connect 或 ConnectAsync,SendAsync 方法将引发异常。

如果您想要与 SendTo 相同的行为,您应该使用SendToAsync

如果您使用的是无连接协议,则无需在调用 SendToAsync 之前使用 BeginConnect、Connect 或 ConnectAsync 方法建立默认远程主机。仅当您打算调用 BeginSend 或 SendAsync 方法时才需要这样做。

于 2018-12-30T11:51:36.433 回答