为什么 UDPSocket.SendAsync() 需要 connect() 方法才能工作?

Why does UDPSocket.SendAsync() requires connect() method to work?

当时我在 C# 中使用 XXXAsync 方法和 socketeventargs 在测试我的控制台应用程序时,数据没有被发送(在本地 - 在一台电脑内)并且在发件人应用程序中没有使用此代码抛出错误。

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("++++++++++++++++++++++++");
}

但是,当 try catch 块中的 connect() 代码未被注释时,此应用成功发送了数据。它也在

时发送了数据
FlashUDP.SendTo("dat1", send_ipep);

代替了

FlashUDP.SendAsync(Sock_Args);

我是不是遗漏了什么,或者这是 udp 的工作方式? 如果

我原以为
"SentTo()" 

无需连接即可工作

"SendAsync()"

也应该在没有连接的情况下工作。 连接对客户端来说不是问题,但对服务器来说是个问题,因为它必须处理许多客户端。 当我不绑定()接收器时,不会发送数据。 有什么解决办法吗? 谢谢!

根据 SendTo documentation 这是预期的行为:

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.

SendAsync documentation(SendAsync 是前面提到的 Send 的异步等价物)然后指出:

The SendAsync method will throw an exception if you do not first call Accept, AcceptAsync, BeginAcceptBeginConnect, Connect, or ConnectAsync.

如果您想要与 SendTo 相同的行为,您应该使用 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.