这是一个 C# 网络编程中异步 Socket 通信的回调函数。ReceiveCallback 函数是当异步接收数据完成时被调用的,而 SendDataCallBack 函数是当异步发送数据完成时被调用的。

在 ReceiveCallback 函数中,首先判断接收到的数据长度是否为 0,如果是 0 则表示客户端已经断开连接,需要关闭 Socket。否则,将接收到的数据复制到一个新的 byte 数组中,并调用 'mReceiveDataEventHandler' 事件处理程序处理数据。最后,继续异步接收数据。

在 SendDataCallBack 函数中,将发送数据的结果长度传递给 'mSendDataEventHandler' 事件处理程序处理。如果发送过程中出现异常,则需要关闭 Socket。

代码示例:

private void ReceiveCallback(IAsyncResult iIAsyncResult)
{
    try
    {
        int length = this.mWorkSocket.EndReceive(iIAsyncResult);
        if (length == 0)
        {
            this.CloseSocket(new Exception('客户端断开连接'));
        }
        else
        {
            this.mReceiveDataEventHandler = ReceiveDataFinish;
            if (this.mReceiveDataEventHandler != null)
            {
                byte[] destinationArray = new byte[length];
                Array.Copy(this.mReceiveBuffer, 0, destinationArray, 0, length);
                this.mReceiveDataEventHandler(this, destinationArray);
            }
            this.mWorkSocket.BeginReceive(this.mReceiveBuffer, 0, this.mReceiveBuffer.Length, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), this);
        }
    }
    catch (Exception exception)
    {
        this.CloseSocket(exception);
    }
}

private void SendDataCallBack(IAsyncResult iIAsyncResult)
{
    try
    {
        int lenth = this.mWorkSocket.EndSend(iIAsyncResult);
        this.mSendDataEventHandler = SendDataFinish;
        if (this.mSendDataEventHandler != null)
        {
            this.mSendDataEventHandler(this, lenth);
        }
    }
    catch (Exception exception)
    {
        this.CloseSocket(exception);
    }
}
C# 异步 Socket 通信回调函数解析

原文地址: https://www.cveoy.top/t/topic/gRc8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录