private void MessageReadCallback(IAsyncResult ar) { string content = string.Empty; int SplitIndex = 0; StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; string parseString = string.Empty; byte[] data; try { int databytesRead = handler.EndReceive(ar); if (databytesRead > 0) { state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, databytesRead)); content = state.sb.ToString(); if (content.Contains("\n")) { do { SplitIndex = content.IndexOf("\n"); parseString = content.Substring(0, SplitIndex); state.sb.Remove(0, SplitIndex + 1); data = Convert.FromBase64String(parseString); parseString = Encoding.UTF8.GetString(data); _MessageSessionContract = SerializeUtility.DeSerialize <MessageSessionContract>(parseString); if (_MessageSessionContract != null) { _MessageSessionContract.MessageContent = Encoding.UTF8.GetString(Convert.FromBase64String(_MessageSessionContract.MessageContent)); if (_MessageInterfaceTable.ContainsKey(_TargetID)) { _MessageInterfaceTable[_TargetID].OnMessageReceive((IMessageContent)_MessageSessionContract); } } } while (state.sb.ToString().Contains("\n")); } handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(MessageReadCallback), state); } else { _ReceiveFlag.Set(); } } catch (Exception e) { //Console.WriteLine(e.ToString()); } }
private void SendMessageTask(string msg) { MessageSessionContract obj = new MessageSessionContract(); obj.TimeTick_String = DateTime.Now.Ticks.ToString(); obj.MessageContent = Convert.ToBase64String(Encoding.UTF8.GetBytes(msg)); string data = Convert.ToBase64String(Encoding.UTF8.GetBytes(SerializeUtility.Serialize(obj))); byte[] SendBytes = Encoding.UTF8.GetBytes(data + "\n"); try { _socket.Send(SendBytes, SendBytes.Length, SocketFlags.None); } catch (Exception e) { // skip } }