现在已经正在使用此 SocketAsyncEventArgs 实例进

本文档展示了一个C#实现的TCP客户端类`DwSocketClient`,该类使用`SocketAsyncEventArgs`进行异步通信。在`ProcessReceive`方法中,由于尝试再次调用`ReceiveAsync`时遇到异常,提示实例正在使用。解决方案是在重新连接时确保正确关闭套接字和资源。`CloseClient`方法已更新,关闭套接字以防止资源冲突。
摘要由CSDN通过智能技术生成
public sealed class DwSocketClient : IDisposable
    {
        private int bufferSize = 10000;
        private Socket _serverSocket;
        private IPEndPoint _hostEndPoint;
        private AutoResetEvent _autoResetEvent;
        private byte[] _byteCallBackMessage;

        private SocketAsyncEventArgs _connectArgs;
        private SocketAsyncEventArgs _sendEventArgs;
        private SocketAsyncEventArgs _receiveEventArgs;

        private string _ip;
        private int _port;
        public DwSocketClient(string ip,int port)
        {
            this._ip = ip;
            this._port = port;

            this._hostEndPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);

            _connectArgs = new SocketAsyncEventArgs();
            _connectArgs.RemoteEndPoint = this._hostEndPoint;
            _connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);

            this._receiveEventArgs = new SocketAsyncEventArgs();
            this._receiveEventArgs.RemoteEndPoint = this._hostEndPoint;
            this._receiveEventArgs.SetBuffer(new Byte[bufferSize], 0, bufferSize);
            this._receiveEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);

            this._sendEventArgs = new SocketAsyncEventArgs();
            this._sendEventArgs.RemoteEndPoint = this._hostEndPoint;
            this._sendEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
        }

        public bool Connect()
        {
            try
            {
                this._autoResetEvent = new AutoResetEvent(false);

                this._serverSocket = new Socket(this._hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                
                _serverSocket.ConnectAsync(_connectArgs);
                this._autoResetEvent.WaitOne(1000*1);

                SocketError errorCode = _connectArgs.SocketError;
                var connected = errorCode == SocketError.Success;
                if (!connected)
                {
                    return connected;
                }
                
                if (!_serverSocket.ReceiveAsync(this._receiveEventArgs))
                {
                    ProcessReceive(this._receiveEventArgs);
                }
                return connected;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void OnConnect(object sender, SocketAsyncEventArgs e)
        {
            this._autoResetEvent.Set();
        }

        private void OnReceive(object sender, SocketAsyncEventArgs e)
        {
            ProcessReceive(e);
        }
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                var allData = new byte[e.BytesTransferred];
                Buffer.BlockCopy(e.Buffer, 0, allData, 0, e.BytesTransferred);

                this._byteCallBackMessage = allData;
                this._autoResetEvent.Set();
                
                //接收后续的数据
                if (!this._serverSocket.ReceiveAsync(e))
                {
                    ProcessReceive(e);
                }
                
            }
            else
            {
               // CloseClient();
            }
        }
        public void CloseClient()
        {
            this._autoResetEvent.Close();
            if (this._serverSocket.Connected)
            {
                //this._serverSocket.Close();
            }
        }
        private void OnSend(object sender, SocketAsyncEventArgs e)
        {
            
        }
        public byte[] Send(byte[] message)
        {
            try
            {
                this._byteCallBackMessage = null;
                
                this._sendEventArgs.SetBuffer(message, 0, message.Length);
                bool isSuccess = _serverSocket.SendAsync(this._sendEventArgs);

                //Thread.Sleep(10*1000);

                this._autoResetEvent.WaitOne(1000 * 5);
                if (this._byteCallBackMessage == null)
                {
                    
                }    
                return this._byteCallBackMessage;
            }
            catch (Exception ex)
            {
                return null;
            }
            
        }
        #region IDisposable Members
        public void Dispose()
        {
            this.CloseClient();
        }
        #endregion
    }

                 
                if (!_serverSocket.ReceiveAsync(this._receiveEventArgs))
                {
                    ProcessReceive(this._receiveEventArgs);
                }

这里报异常:现在已经正在使用此 SocketAsyncEventArgs 实例进

public sealed class DwSocketClient : IDisposable
    {
        private int bufferSize = 10000;
        private Socket _serverSocket;
        private IPEndPoint _hostEndPoint;
        private AutoResetEvent _autoResetEvent;
        private byte[] _byteCallBackMessage;

        private SocketAsyncEventArgs _connectArgs;
        private SocketAsyncEventArgs _sendEventArgs;
        private SocketAsyncEventArgs _receiveEventArgs;

        private string _ip;
        private int _port;
        public DwSocketClient(string ip,int port)
        {
            this._ip = ip;
            this._port = port;

            this._hostEndPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);

            _connectArgs = new SocketAsyncEventArgs();
            _connectArgs.RemoteEndPoint = this._hostEndPoint;
            _connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);

            this._receiveEventArgs = new SocketAsyncEventArgs();
            this._receiveEventArgs.RemoteEndPoint = this._hostEndPoint;
            this._receiveEventArgs.SetBuffer(new Byte[bufferSize], 0, bufferSize);
            this._receiveEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);

            this._sendEventArgs = new SocketAsyncEventArgs();
            this._sendEventArgs.RemoteEndPoint = this._hostEndPoint;
            this._sendEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
        }

        public bool Connect()
        {
            try
            {
                this._autoResetEvent = new AutoResetEvent(false);

                this._serverSocket = new Socket(this._hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                
                _serverSocket.ConnectAsync(_connectArgs);
                this._autoResetEvent.WaitOne(1000*1);

                SocketError errorCode = _connectArgs.SocketError;
                var connected = errorCode == SocketError.Success;
                if (!connected)
                {
                    return connected;
                }
                
                if (!_serverSocket.ReceiveAsync(this._receiveEventArgs))
                {
                    ProcessReceive(this._receiveEventArgs);
                }
                return connected;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void OnConnect(object sender, SocketAsyncEventArgs e)
        {
            this._autoResetEvent.Set();
        }

        private void OnReceive(object sender, SocketAsyncEventArgs e)
        {
            ProcessReceive(e);
        }
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                var allData = new byte[e.BytesTransferred];
                Buffer.BlockCopy(e.Buffer, 0, allData, 0, e.BytesTransferred);

                this._byteCallBackMessage = allData;
                this._autoResetEvent.Set();
                
                //接收后续的数据
                if (!this._serverSocket.ReceiveAsync(e))
                {
                    ProcessReceive(e);
                }
                
            }
            else
            {
               // CloseClient();
            }
        }
        public void CloseClient()
        {
            this._autoResetEvent.Close();
            if (this._serverSocket.Connected)
            {
                this._serverSocket.Close();
            }
        }
        private void OnSend(object sender, SocketAsyncEventArgs e)
        {
            
        }
        public byte[] Send(byte[] message)
        {
            try
            {
                this._byteCallBackMessage = null;
                
                this._sendEventArgs.SetBuffer(message, 0, message.Length);
                bool isSuccess = _serverSocket.SendAsync(this._sendEventArgs);

                //Thread.Sleep(10*1000);

                this._autoResetEvent.WaitOne(1000 * 5);
                if (this._byteCallBackMessage == null)
                {
                    
                }    
                return this._byteCallBackMessage;
            }
            catch (Exception ex)
            {
                return null;
            }
            
        }
        #region IDisposable Members
        public void Dispose()
        {
            this.CloseClient();
        }
        #endregion
    }

        public void CloseClient()
        {
            this._autoResetEvent.Close();
            if (this._serverSocket.Connected)
            {
                this._serverSocket.Close();
            }
        }

重连时要把连接关闭掉,解决问题。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值