C # 비동기 데이터 전송을 수신하고 UDP

UDP : 사용자 데이터 그램 프로토콜 사용자 데이터 그램 프로토콜은 비 연결형 전송 프로토콜입니다.
그래서 같은 서버에 직접 데이터를 전송할 수있는 서버에 TCP 연결에 따라 ConnectAsync를 사용하지.

참조 : 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.

반환 값은 단순히 사실로 대기중인 경우, 성공적으로 트리거에게 콜백 이벤트를받은
수동으로 실행에 동기화 프로세스가 완료되었음을 나타냅니다 false 인 경우 다음 콜백 이벤트의 필요성을 트리거하지 않습니다.
SendToAsync는 이유
, 다음 코드를해야합니다 :

...省略定义一些成员变量: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
    {
    	//没有接收到数据
    }
}
출시 다섯 개 원래 기사 · 원의 찬양 3 · 조회수 2794

추천

출처blog.csdn.net/a543658883/article/details/104575201