C# 异步UDP发送接收数据
作者:互联网
UDP:User Datagram Protocol 用户数据报协议,是一个无连接的传输协议。
所以不像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.
简单来说就是如果返回值是true就等待处理,接收成功了会触发回调事件
如果是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
{
//没有接收到数据
}
}
JepChen
发布了5 篇原创文章 · 获赞 3 · 访问量 2795
私信
关注
标签:...,UDP,SocketAsyncEventArgs,C#,Completed,saea,connectSocket,SocketError,接收数据 来源: https://blog.csdn.net/a543658883/article/details/104575201