C#委托
异步委托【理解】
异步委托【原理】
异步委托【实验】
注意:Action.BeginInvoke方法是在.NET Framework中引入的,而在.NET Core和.NET 5及更高版本中已被弃用。如果在使用异步编程时需要进行委托的异步调用,可以使用.NET Core和.NET 5及更高版本中提供的Task.Run方法或Task.Factory.StartNew方法代替。
当客户端发起连接时,如果网络情况不好或服务端没有回应,同步Connect方法会使客户端卡住一段时间。而在卡住的时间内,用户不能做任何操作,游戏体验感会很差。
BeginConnect和EndConnect的调用形式为:
public IAsyncResult BeginConnect(
string host,
int port,
AsyncCallback requestCallback,
object state
)
参数 | 含义 |
---|---|
host | 远程主机的IP |
port | 远程主机的端口 |
requestCallback | 回调函数 |
state | 用户自定义对象 |
注意:回调函数是一个AsyncCallback委托,回调函数的参数形式必须是:void Name(IAsyncResult ar) 。
public void EndConnect(
IAsyncResult asyncResult
)
基于异步Connect实现异步连接后的客户端程序如下:
public class Echo : MonoBehaviour
{
private Socket socket;
public InputField inputField;
public Text text;
private byte[] readBuff = new byte[1024];
private string recvStr = "";
//异步Connection
public void Connection()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//启动新线程执行Connect
socket.BeginConnect("127.0.0.1", 8888, ConnectCallback, socket);
}
//回调方法
public void ConnectCallback(IAsyncResult ar)
{
try
{
//传参为连接socket(强制类型转换)
Socket socket = (Socket)ar.AsyncState;
//EndConnect结束线程
socket.EndConnect(ar);
Debug.Log("Socket Connect Succ");
}
catch (SocketException e)
{
Debug.Log("Socket Connect fail:"+e.ToString());
}
}
}
注意:回调函数中需要得到委托实例,然后才可以调用EndInvoke方法来获取异步方法执行的结果。
Receive是个阻塞方法,直到收到服务端数据为止。如果服务端没有回应,则客户端程序会卡死无响应。而BeginReceive和EndReceive方法是解决这个问题的关键。
BeginReceive和EndReceive的调用形式为:
public IAsyncResult BeginReceive(
byte[] buffer;
int offset;
int size;
SocketFlags socketFlags;
AsyncCallback requestCallback,
object state
)
参数 | 含义 |
---|---|
buffer | 存储接收到的数据 |
offset | buffer中存储数据的位置 |
size | 最多接收的字节数 |
socketFlags | SocketFlags值的按位组合,这里设置为0 |
requestCallback | 回调函数 |
object | 用户自定义对象 |
public int EndReceive(
IAsyncResult asyncResult;
)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
public class Echo : MonoBehaviour
{
private Socket socket;
public InputField inputField;
public Text text;
private byte[] readBuff = new byte[1024];
private string recvStr = "";
//异步Connection
public void Connection()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//启动新线程执行Connect
socket.BeginConnect("127.0.0.1", 8888, ConnectCallback, socket);
}
//回调方法
public void ConnectCallback(IAsyncResult ar)
{
try
{
//传参为连接socket(强制类型转换)
Socket socket = (Socket)ar.AsyncState;
//EndConnect结束线程
socket.EndConnect(ar);
Debug.Log("Socket Connect Succ");
//客户端连上服务器就开始接收信息(存储于readBuff)
socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
}
catch (SocketException e)
{
Debug.Log("Socket Connect fail:"+e.ToString());
}
}
public void ReceiveCallback(IAsyncResult ar)
{
try
{
//处理接收到的数据readBuff
Socket socket = (Socket)ar.AsyncState;
int count = socket.EndReceive(ar);
//得到接收字符串recvStr
string s = System.Text.Encoding.Default.GetString(readBuff, 0, count);
recvStr = s ;
//继续在独立线程中接收客户端消息(更新readBuff,并处理为字符串recvStr)
socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
}
catch (SocketException e)
{
Debug.Log("Socket Receive fail:"+e.ToString());
}
}
public void Send()
{
string sendStr = inputField.text;
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
socket.Send(sendBytes);
}
public void Update()
{
//显示客户端接收到的消息recvStr
text.text = recvStr;
}
}
Send是个阻塞方法,直到Send成功将发送数据写入操作系统的发送缓冲区为止。异步Send方法不会卡住程序。
BeginSend和EndSend的调用形式为:
public IAsyncResult BeginSend(
byte[] buffer;
int offset;
int size;
SocketFlags socketFlags;
AsyncCallback callback,
object state
)
参数 | 含义 |
---|---|
buffer | 存储接收到的数据 |
offset | buffer中发送数据的位置 |
size | 要发送的字节数 |
socketFlags | SocketFlags值的按位组合,这里设置为0 |
callback | 回调函数 |
object | 用户自定义对象 |
public int EndSend(
IAsyncResult asyncResult;
)
注意:EndSend方法返回值代表发送的字节数,如果发送失败会抛出异常。一般情况下,EndSend方法返回值与要发送的数据长度相同,代表全部发完,但有时会不同,如果EndSend的返回值指示数据未全部发完,需要再次调用BeginSend方法发出未发出的数据。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
public class Echo : MonoBehaviour
{
private Socket socket;
public InputField inputField;
public Text text;
private byte[] readBuff = new byte[1024];
private string recvStr = "";
//异步Connection
public void Connection()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//启动新线程执行Connect
socket.BeginConnect("127.0.0.1", 8888, ConnectCallback, socket);
}
//回调方法
public void ConnectCallback(IAsyncResult ar)
{
try
{
//传参为连接socket(强制类型转换)
Socket socket = (Socket)ar.AsyncState;
//EndConnect结束线程
socket.EndConnect(ar);
Debug.Log("Socket Connect Succ");
//客户端连上服务器就开始接收信息(存储于readBuff)
socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
}
catch (SocketException e)
{
Debug.Log("Socket Connect fail:"+e.ToString());
}
}
public void ReceiveCallback(IAsyncResult ar)
{
try
{
//处理接收到的数据readBuff
Socket socket = (Socket)ar.AsyncState;
int count = socket.EndReceive(ar);
//得到接收字符串recvStr
string s = System.Text.Encoding.Default.GetString(readBuff, 0, count);
recvStr = s + "\n" + recvStr;
//继续在独立线程中接收客户端消息(更新readBuff,并处理为字符串recvStr)
socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
}
catch (SocketException e)
{
Debug.Log("Socket Receive fail:"+e.ToString());
}
}
public void Send()
{
string sendStr = inputField.text;
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
socket.BeginSend(sendBytes,0,sendBytes.Length,0,SendCallback,socket);
}
public void SendCallback(IAsyncResult ar)
{
try
{
Socket socket = (Socket)ar.AsyncState;
int count = socket.EndSend(ar);
Debug.Log("Socket Send succ"+count);
}catch(SocketException ex)
{
Debug.Log("Socket Send fail:" + ex.ToString());
}
}
public void Update()
{
//显示客户端接收到的消息recvStr
text.text = recvStr;
}
}