public void ProcessReceive(MySocketAsyncEventArgs e) { if (e.BytesTransferred <= 0 || e.SocketError != SocketError.Success) { OnClosed(e); return; } if (e.LastOperation != SocketAsyncOperation.Receive) { return; } if (e.BytesTransferred > 0) { if (e.SocketError == SocketError.Success) { int byteTransferred = e.BytesTransferred; string received = Encoding.Unicode.GetString(e.Buffer, e.Offset, byteTransferred); ////检查消息的准确性 //string[] msg = RequestHandler.GetActualString(received); //foreach (string m in msg) // OnMsgReceived(((MySocketAsyncEventArgs)e).UID, m); //可以在这里设一个停顿来实现间隔时间段监听,这里的停顿是单个用户间的监听间隔 //发送一个异步接受请求,并获取请求是否为成功 bool willRaiseEvent = (e.UserToken as Socket).ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } } } }
public void Send(MySocketAsyncEventArgs e, string uid, string msg) { int i = 0; try { string _msg = string.Format(msg, msg.Length, msg); byte[] _sendBuffer = Encoding.Unicode.GetBytes(_msg); e.SetBuffer(_sendBuffer, 0, _sendBuffer.Length); bool _willRaiseEvent = (e.UserToken as Socket).SendAsync(e); if (!_willRaiseEvent) { this.ProcessSend(e); } } catch (Exception ex) { if (i <= 5) { i++; //如果发送出现异常就延迟0.01秒再发 Thread.Sleep(10); Send(e, uid, msg); } else { Send(e, uid, ex.ToString()); } } }
public virtual void OnClosed(MySocketAsyncEventArgs e) { if (Closed != null) { Closed(this, e); } }
/// <summary> /// send message /// </summary> /// <param name="uid"></param> /// <param name="msg"></param> public void Send(string uid, string msg) { if (string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(msg)) { return; } DuplexSocketAsyncEventArgsWithId _socket = m_readWritePool.FindByUID(uid); //说明用户已经断开 //100 发送成功 //200 发送失败 //300 用户不在线 //其它 表示异常的信息 if (_socket == null) { OnSended(uid, MessageType.UseOffline.ToString()); } else { string _msgTmpl = @"[length={0}]{1}"; MySocketAsyncEventArgs _e = _socket.SendSAEA; if (_e.SocketError == SocketError.Success) { int _i = 0; try { string _msg = string.Format(_msgTmpl, msg.Length, msg); byte[] _sendBuffer = Encoding.Unicode.GetBytes(_msg); _e.SetBuffer(_sendBuffer, 0, _sendBuffer.Length); bool _willRaiseEvent = (_e.UserToken as Socket).SendAsync(_e); if (!_willRaiseEvent) { this.ProcessSend(_e); } } catch (Exception ee) { if (_i <= 5) { _i++; //如果发送出现异常就延迟0.01秒再发 Thread.Sleep(10); Send(uid, msg); } else { OnSended(uid, ee.ToString()); } } } else { OnSended(uid, MessageType.Failed.ToString()); this.CloseClientSocket(_e.UID, false); } } }
/// <summary> /// 发送信息 /// </summary> /// <param name="message"></param> public void SendMessage(string message) { if (this.connected) { message = string.Format("[length={0}]{1}", message.Length, message); byte[] sendBuffer = Encoding.Unicode.GetBytes(message); MySocketAsyncEventArgs senderSocketAsyncEventArgs = _readWirted.SendSAEA; senderSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length); senderSocketAsyncEventArgs.RemoteEndPoint = this.hostEndPoint; clientSocket.SendAsync(senderSocketAsyncEventArgs); } else { throw new SocketException((int)SocketError.NotConnected); } }
public void ProcessSend(MySocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { OnClosed(e); return; } AsyncUserToken token = (AsyncUserToken)e.UserToken; bool willRaiseEvent = token.Socket.ReceiveAsync(e); if (!willRaiseEvent) { ProcessReceive(e); } }
/// <summary> /// 连接服务端 /// </summary> public bool Connect() { MySocketAsyncEventArgs connectArgs = new MySocketAsyncEventArgs("Connect"); connectArgs.UserToken = new AsyncUserToken(clientSocket); connectArgs.RemoteEndPoint = this.hostEndPoint; connectArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnConnect); clientSocket.ConnectAsync(connectArgs); //等待连接结果 autoConnectEvent.WaitOne(); SocketError errorCode = connectArgs.SocketError; if (errorCode == SocketError.Success) { this.m_bufferManager.InitBuffer(); _readWirted = new DuplexSocketAsyncEventArgsWithId(); //_readWirted.State = true; _readWirted.ReceiveSAEA.Completed += OnReceive; _readWirted.SendSAEA.Completed += OnSend; _readWirted.ReceiveSAEA.UserToken = new AsyncUserToken(clientSocket); _readWirted.SendSAEA.UserToken = new AsyncUserToken(clientSocket); this.m_bufferManager.SetBuffer(_readWirted.ReceiveSAEA); if (!(_readWirted.ReceiveSAEA.UserToken as AsyncUserToken).Socket.ReceiveAsync(_readWirted.ReceiveSAEA)) { ProcessReceive(_readWirted.ReceiveSAEA); } if (StartListenThread != null) { StartListenThread(); } return(true); } else { //throw new SocketException((Int32)errorCode); return(false); } }
//constructor internal DuplexSocketAsyncEventArgsWithId() { m_receivesaea = new MySocketAsyncEventArgs("Receive"); m_sendsaea = new MySocketAsyncEventArgs("Send"); }