//异步请求连接网络回调方法 protected void MyProcessConnect(Socket socket, object state, MySocketAsyncArgs e) { if (e != null && e.SocketError != SocketError.Success) { m_InConnecting = false; OnError(new SocketException((int)e.SocketError)); return; } if (socket == null) { m_InConnecting = false; OnError(new SocketException((int)SocketError.ConnectionAborted)); return; } Client = socket; m_InConnecting = false; Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); //连接成功,子类具体响应处理 MyOnGetSocket(e); }
//异步创建连接的回调方法 private static void MyConnectionCallback(IAsyncResult ar) { MySocketAsyncArgs args = (MySocketAsyncArgs)ar.AsyncState; try { args.AcceptSocket.EndConnect(ar); //args.AcceptSocket.Blocking = true; args.AcceptSocket.SendTimeout = 10; args.AcceptSocket.ReceiveTimeout = 10; args.SocketError = SocketError.Success; //连接成功,主动调用原事件 args.Callback(args.AcceptSocket, args.State, args); } catch (System.Exception ex) { // 错误处理 if (ex.GetType() == typeof(SocketException)) { if (((SocketException)ex).SocketErrorCode == SocketError.ConnectionRefused) { //连接被服务器拒绝 throw new Exception("socket error because of connection refused."); } else { //连接丢失 throw new Exception("socket error: " + ex.Message); } } if (args.AcceptSocket.Connected) { args.AcceptSocket.Shutdown(SocketShutdown.Receive); args.AcceptSocket.Close(0); } else { args.AcceptSocket.Close(); } } }
//异步请求接收消息 void MyStartReceive(MySocketAsyncArgs e) { var client = Client; if (client == null) { return; } try { client.BeginReceive(e.Buffer, e.Offset, e.Count, 0, new AsyncCallback(MyReceiveCallback), e); } catch (SocketException exc) { if (!IsIgnorableSocketError(exc.ErrorCode)) { OnError(exc); } if (EnsureSocketClosed(client)) { OnClosed(); } return; } catch (Exception ex) { if (!IsIgnorableException(ex)) { OnError(ex); } if (EnsureSocketClosed(client)) { OnClosed(); } return; } }
protected abstract void MyOnGetSocket(MySocketAsyncArgs e);
protected override void MyOnGetSocket(MySocketAsyncArgs e) { }
//异步接收消息回调方法 protected void MyReceiveCallback(IAsyncResult ar) { MySocketAsyncArgs e = (MySocketAsyncArgs)ar.AsyncState; if (e.SocketError != SocketError.Success) { if (EnsureSocketClosed()) { OnClosed(); } if (!IsIgnorableSocketError((int)e.SocketError)) { OnError(new SocketException((int)e.SocketError)); } return; } var client = Client; if (client == null) { return; } //接收数据 try { e.BytesTransferred = e.AcceptSocket.EndReceive(ar); if (e.BytesTransferred == 0) { if (EnsureSocketClosed()) { OnClosed(); } return; } OnDataReceived(e.Buffer, e.Offset, e.BytesTransferred); } catch (SocketException exc) { if (!IsIgnorableSocketError(exc.ErrorCode)) { OnError(exc); } if (EnsureSocketClosed(client)) { OnClosed(); } return; } catch (Exception ex) { if (!IsIgnorableException(ex)) { OnError(ex); } if (EnsureSocketClosed(client)) { OnClosed(); } return; } //下一轮接收数据 MyStartReceive(e); }