C # asynchronous data transmitting and receiving UDP

UDP: User Datagram Protocol User Datagram Protocol is a connectionless transport protocol.
So as not to use ConnectAsync to TCP connection to the server can send data directly to the server.

Reference: MSDN

public bool ReceiveFromAsync (System.Net.Sockets.SocketAsyncEventArgs e);

Returns
Boolean
true if the I/O operation is pending. The Completed event on the e parameter will be raised upon completion of the operation.

false if the I/O operation completed synchronously. In this case, The Completed event on the e parameter will not be raised and the e object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation.

If the return value is simply waiting to be true, successfully received triggers a callback event
if it is false it indicates that the synchronization process is complete, then the callback event does not trigger the need to manually executed.
SendToAsync also a reason
, and will have the following code:

...省略定义一些成员变量:connectSocket,endPoint 等
...省略(构造函数,传入ip和port)...
        connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress address;
        if (!IPAddress.TryParse(ip, out address)) // 尝试解析IP,万一它是一个域名呢
        {
            try
            {
                IPHostEntry host = Dns.GetHostEntry(ip);
                address = host.AddressList[0];
            }
            catch (Exception)
            {
            	Console.WriteLine("IP解析错误!");
            }
        }
        endPoint = new IPEndPoint(address, port);
...

...省略(定义一个“发消息”方法,传入byte[] buff)...
    SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
    saea.SetBuffer(buff, 0, buff.Length);
    saea.UserToken = connectSocket;
    saea.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
    saea.RemoteEndPoint = endPoint;
    if (!connectSocket.SendToAsync(saea))
    {
        IO_Completed(null, saea);
    }
...

private void IO_Completed(object sender, SocketAsyncEventArgs e)
{
    switch (e.LastOperation)
    {
        case SocketAsyncOperation.ReceiveFrom:
            ProcessReceive(e);
            break;
        case SocketAsyncOperation.SendTo:
            ProcessSend(e);
            break;
        default:
            Console.WriteLine(e.LastOperation);
            break;
    }
}
/// <summary>
/// 处理udp客户端发送的结果
/// </summary>
/// <param name="e"></param>
private void ProcessSend(SocketAsyncEventArgs e)
{
    if (e.SocketError == SocketError.Success)
    {
    	// 发送成功就可以准备接收
        if (!connectSocket.ReceiveFromAsync(e))
            IO_Completed(null, e);
    }
    else
    {
    	// 发送失败
    }
}
/// <summary>
/// 处理接受到的udp服务器数据
/// </summary>
/// <param name="e"></param>
private void ProcessReceive(SocketAsyncEventArgs e)
{
    if (e.BytesTransferred > 0 && e.SocketError == SocketError.MessageSize)
    {
    	//处理接收到的数据(e.Buffer);
    }
    else
    {
    	//没有接收到数据
    }
}
Released five original articles · won praise 3 · Views 2794

Guess you like

Origin blog.csdn.net/a543658883/article/details/104575201