public void Send(ClientSocket clientSocket, MessageBase messageBase) { if (clientSocket == null || !clientSocket.Socket.Connected) { return; } try { //分为三部分,头:总协议长度;名字;协议内容。 byte[] nameBytes = _messageParser.EncodeName(messageBase); byte[] bodyBytes = _messageParser.EncodeContent(messageBase); int len = nameBytes.Length + bodyBytes.Length; byte[] byteHead = BitConverter.GetBytes(len); byte[] sendBytes = new byte[byteHead.Length + len]; Array.Copy(byteHead, 0, sendBytes, 0, byteHead.Length); Array.Copy(nameBytes, 0, sendBytes, byteHead.Length, nameBytes.Length); Array.Copy(bodyBytes, 0, sendBytes, byteHead.Length + nameBytes.Length, bodyBytes.Length); try { clientSocket.Socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, null, null); } catch (SocketException ex) { Debug.LogError("Socket BeginSend Error:" + ex); } } catch (SocketException ex) { Debug.LogError("Socket发送数据失败:" + ex); } }
/// <summary> /// 发送数据到服务器 /// </summary> /// <param name="msgBase"></param> public void SendMessage(MessageBase msgBase) { if (_socket == null || !_socket.Connected) { return; } if (_connecting) { Debug.LogError("正在链接服务器中,无法发送消息!"); return; } if (_closing) { Debug.LogError("正在关闭链接中,无法发送消息!"); return; } try { byte[] nameBytes = _messageParser.EncodeName(msgBase); byte[] bodyBytes = _messageParser.EncodeContent(msgBase); int len = nameBytes.Length + bodyBytes.Length; byte[] byteHead = BitConverter.GetBytes(len); byte[] sendBytes = new byte[byteHead.Length + len]; Array.Copy(byteHead, 0, sendBytes, 0, byteHead.Length); Array.Copy(nameBytes, 0, sendBytes, byteHead.Length, nameBytes.Length); Array.Copy(bodyBytes, 0, sendBytes, byteHead.Length + nameBytes.Length, bodyBytes.Length); ByteArray ba = new ByteArray(sendBytes); int count = 0; lock (_writeQueue) { _writeQueue.Enqueue(ba); count = _writeQueue.Count; } if (count == 1) { _socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallBack, _socket); } } catch (Exception ex) { Debug.LogError("SendMessage error:" + ex.ToString()); Close(); } }