void OnRecievePacket(IAsyncResult result) { try { Socket socket = result.AsyncState as Socket; int len = socket.EndReceive(result); if (len != packetSize) { throw new OverflowException("packet size not equal!"); } PostNotification(() => { int typeid = PacketHelper.UnpackHeader(buffer); if (!handlerMap.ContainsKey(typeid)) { Debug.LogWarning("type id not registered: " + typeid.ToString()); return; } handlerMap[typeid](typeid, buffer); }); //recieve next packet RecievePacket(socket); } catch (SocketException ex) { Close(); PostNotification(() => { networkErrorCallback(ex.Message); }); Debug.LogException(ex); } catch (Exception ex) { //pass } }
/// <summary> /// Send the specified packet type id and packet data. /// </summary> /// <param name='typeId'> /// packet type identifier. /// </param> /// <param name='data'> /// packet data /// </param> public void Send(int typeId, byte[] data) { int length = data.Length + 2; byte[] needsend = new byte[data.Length + 4]; byte[] header = PacketHelper.PackHeader(length); byte[] typeheader = PacketHelper.PackHeader(typeId); for (int i = 0; i < header.Length; i++) { needsend[i] = header[i]; } for (int i = 0; i < typeheader.Length; i++) { needsend[i + 2] = typeheader[i]; } for (int i = 0; i < data.Length; i++) { needsend[i + 4] = data[i]; } if (networkState == NetworkState.Connected) { Debug.Log("send data: " + typeId); socket.BeginSend(needsend, 0, needsend.Length, SocketFlags.None, OnSendResult, socket); } }
void OnRecieveHeader(IAsyncResult result) { try { Socket socket = result.AsyncState as Socket; int recvLen = socket.EndReceive(result); if (recvLen == 0) { throw new SocketException(10054); } packetSize = PacketHelper.UnpackHeader(header); buffer = new byte[packetSize]; socket.BeginReceive(buffer, 0, packetSize, SocketFlags.None, OnRecievePacket, socket); } catch (SocketException ex) { Close(); PostNotification(() => { networkErrorCallback(ex.Message); }); Debug.LogException(ex); } catch (Exception ex) { //pass } }