public override void init() { try { mSocketFactory.init(); mHeartBeatMaxTime = mGameConfig.getFloatParam(GAME_DEFINE_FLOAT.GDF_HEART_BEAT_NITERVAL); // 获得IP和端口号 IPAddress serverIP = null; string ipString = mGameConfig.getStringParam(GAME_DEFINE_STRING.GDS_TCP_SERVER_IP); if (ipString == "") { IPAddress[] ipList = Dns.GetHostAddresses(mGameConfig.getStringParam(GAME_DEFINE_STRING.GDS_TCP_HOST_NAME)); if (ipList.Length > 0) { serverIP = ipList[0]; } } else { serverIP = IPAddress.Parse(ipString); } int port = (int)mFrameConfig.getFloatParam(GAME_DEFINE_FLOAT.GDF_SOCKET_PORT); // 创建socket mServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); mServerSocket.Connect(serverIP, port); } catch (Exception) { mServerSocket = null; CommandSocketManagerNetState cmd = newCmd(out cmd); cmd.mNetState = NET_STATE.NS_NET_CLOSE; pushCommand(cmd, this); return; } mSendThread.start(sendSocket); mReceiveThread.start(receiveSocket); }
// 接收Socket消息 protected bool receiveSocket() { try { IPEndPoint endpoint = null; if (endpoint == null) { endpoint = new IPEndPoint(IPAddress.Any, 0); } EndPoint ep = (EndPoint)endpoint; byte[] recvBuff = null; if (recvBuff == null) { recvBuff = new byte[mMaxReceiveCount]; } int nRecv = mServerSocket.ReceiveFrom(recvBuff, ref ep); if (nRecv <= 0) { CommandSocketManagerNetState cmd = newCmd(out cmd, true, true); cmd.mNetState = NET_STATE.NS_NET_CLOSE; pushDelayCommand(cmd, this); return(false); } int index = 0; while (true) { if (index + sizeof(short) > nRecv) { break; } // 读取包类型(short) PACKET_TYPE type = (PACKET_TYPE)BinaryUtility.readShort(recvBuff, ref index); // 客户端接收到的必须是SC类型的 if (type <= PACKET_TYPE.PT_SC_MIN || type >= PACKET_TYPE.PT_SC_MAX) { UnityUtility.logError("packet type error : " + type); break; } int packetSize = mSocketFactory.getPacketSize(type); if (packetSize >= 0) { // 读取消息长度(short) short realDataSize = BinaryUtility.readShort(recvBuff, ref index); if (realDataSize != packetSize) { UnityUtility.logError("error : wrong packet size! type : " + type + "readed : " + realDataSize + ", packet size : " + packetSize, false); break; } if (packetSize > nRecv - sizeof(short)) { UnityUtility.logError("error : wrong packet data! packet : " + type + ", need size : " + packetSize + ", receive size : " + (nRecv - sizeof(PACKET_TYPE)), false); break; } mReceiveLock.waitForUnlock(); if (packetSize != 0) { byte[] recvData = new byte[packetSize]; // 读取消息内容(byte[]) BinaryUtility.readBytes(recvBuff, ref index, recvData); mRecieveList.Add(new INPUT_ELEMENT(type, recvData)); } else { byte[] recvData = null; mRecieveList.Add(new INPUT_ELEMENT(type, recvData)); } mReceiveLock.unlock(); // 该段消息内存已经解析完了 if (index == nRecv) { break; } } // 如果消息解析发生错误,则不再解析 else { break; } } } catch (SocketException) { CommandSocketManagerNetState cmd = newCmd(out cmd, true, true); cmd.mNetState = NET_STATE.NS_SERVER_CLOSE; pushDelayCommand(cmd, this); return(false); } return(true); }