public void init(IPAddress ip, int port) { try { mHeartBeatMaxTime = mGameConfig.getFloatParam(GAME_DEFINE_FLOAT.GDF_HEART_BEAT_NITERVAL); // 创建socket mServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); mServerSocket.Connect(ip, port); } catch (Exception e) { logInfo("init socket exception : " + e.Message + ", stack : " + e.StackTrace, LOG_LEVEL.LL_FORCE); mServerSocket = null; CommandSocketConnectNetState cmd = newCmd(out cmd); cmd.mNetState = NET_STATE.NS_NET_CLOSE; pushCommand(cmd, this); return; } mSendThread.start(sendSocket); mReceiveThread.start(receiveSocket); }
// 接收Socket消息 protected void receiveSocket(ref bool run) { if (mServerSocket == null) { run = false; return; } try { IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0); EndPoint ep = endpoint; int nRecv = mServerSocket.ReceiveFrom(mRecvBuff, ref ep); if (nRecv <= 0) { CommandSocketConnectNetState cmd = newCmd(out cmd, true, true); if (cmd != null) { cmd.mNetState = NET_STATE.NS_NET_CLOSE; pushDelayCommand(cmd, this); } run = false; return; } int index = 0; while (true) { if (index + GameDefine.PACKET_HEADER_SIZE > nRecv) { break; } // 读取包类型 PACKET_TYPE type = (PACKET_TYPE)readInt(mRecvBuff, ref index); // 客户端接收到的必须是SC类型的 if (type <= PACKET_TYPE.PT_SC_MIN || type >= PACKET_TYPE.PT_SC_MAX) { string info = "packet type error : " + type; GameUtility.messageOK(info, true); UnityUtility.logError(info, false); break; } int packetSize = mSocketManager.getPacketSize(type); if (packetSize >= 0) { // 读取消息长度 int realDataSize = readInt(mRecvBuff, ref index); if (realDataSize != packetSize) { string info = "wrong packet size! type : " + type + ", readed : " + realDataSize + ", packet size : " + packetSize; GameUtility.messageOK(info, true); UnityUtility.logError(info, false); break; } if (packetSize > nRecv - GameDefine.PACKET_HEADER_SIZE) { string info = "wrong packet data! packet : " + type + ", need size : " + packetSize + ", receive size : " + (nRecv - sizeof(PACKET_TYPE)); GameUtility.messageOK(info, true); UnityUtility.logError(info, false); break; } if (packetSize != 0) { byte[] recvData = new byte[packetSize]; // 读取消息内容(byte[]) readBytes(mRecvBuff, ref index, recvData); mRecieveList.addToBuffer(new INPUT_ELEMENT(type, recvData)); } else { mRecieveList.addToBuffer(new INPUT_ELEMENT(type, null)); } // 该段消息内存已经解析完了 if (index == nRecv) { break; } } // 如果消息解析发生错误,则不再解析 else { break; } } } catch (SocketException) { CommandSocketConnectNetState cmd = newCmd(out cmd, true, true); if (cmd != null) { cmd.mNetState = NET_STATE.NS_SERVER_CLOSE; pushDelayCommand(cmd, this); } run = false; return; } }