/// <summary> /// Use underline socket to send protocol message async. /// </summary> /// <param name="vMessage">The protocol message to be sended.</param> public void SendMessage(System.Object vMsg) { Log.Info("一个消息需要发送"); if (State != ConnectionState.Established) { Log.Info("一个消息需要发送 1"); Debug.WriteLine(String.Format("SendMessage Error:in State {0}", State)); return; } if (vMsg == null) { Log.Info("一个消息需要发送 2"); Debug.WriteLine(String.Format("SendMessage Error:vMsg is null")); return; } ArraySegment <Byte> sndBuf = ProtoHelper.EncodeMessage(vMsg, vMsg is IResponse); SocketAsyncEventArgs sendEventArgs = new SocketAsyncEventArgs(); sendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnCompletedForSend); sendEventArgs.SetBuffer(sndBuf.Array, sndBuf.Offset, sndBuf.Count); Debug.WriteLine(string.Format("SendMessage Send {0}", vMsg.GetType().Name)); Log.Info(string.Format("SendMessage Send {0}", vMsg.GetType().Name)); if (!ConnSocket.SendAsync(sendEventArgs)) { OnCompletedForSendImpl(sendEventArgs); sendEventArgs.Dispose(); } }
public void Send(byte[] bytes, int length, int offset = 0) { if (!IsConnected) { return; } SendSocketAsyncEventArgsExt sendArg = ObjectAllocatorHolder <SendSocketAsyncEventArgsExt> .Allocate(); sendArg.Completed += OnSendComplete; var sendMs = sendArg.SendBuffer; sendMs.Position = 0; sendMs.SetLength(0); var lenArray = BitConverter.GetBytes(length); if (!_littleEndian) { sendMs.WriteByte(lenArray[3]); sendMs.WriteByte(lenArray[2]); sendMs.WriteByte(lenArray[1]); sendMs.WriteByte(lenArray[0]); } else { sendMs.WriteByte(lenArray[0]); sendMs.WriteByte(lenArray[1]); sendMs.WriteByte(lenArray[2]); sendMs.WriteByte(lenArray[3]); } sendMs.Write(bytes, offset, length); sendArg.SetBuffer(sendMs.GetBuffer(), 0, (int)sendMs.Length); //Logger.Debug("RealSendMsg"); var async = ConnSocket.SendAsync(sendArg); if (!async) { OnSend(sendArg); } }