/// <summary> /// 协议格式: /// SIZE : 4 | TYPE : 4 | MsgID : 4 | PACKET : dynamic /// </summary> /// <typeparam name="T">向服务器发送的packet的类型</typeparam> /// <param name="networkMessage">向服务器发送的请求的类型</param> /// <param name="packet">向服务器发送的packet</param> private void DoBeginSendPacket <T>(ENetworkMessage networkMessage, T packet, byte[] msgID) where T : global::ProtoBuf.IExtensible { try { byte[] sendBuffer = new byte[_socket.SendBufferSize]; MemoryStream streamForProto = new MemoryStream(); Serializer.Serialize <T>(streamForProto, packet); int bufferSize = HEAD_SIZE * HEAD_NUM + (int)streamForProto.Length; byte[] bufferSizeBytes = MiniConverter.IntToBytes(bufferSize); byte[] networkMessageBytes = MiniConverter.IntToBytes((int)networkMessage); Array.Copy(bufferSizeBytes, 0, sendBuffer, HEAD_SIZE * 0, HEAD_SIZE); Array.Copy(networkMessageBytes, 0, sendBuffer, HEAD_SIZE * 1, HEAD_SIZE); Array.Copy(msgID, 0, sendBuffer, HEAD_SIZE * 2, HEAD_SIZE); Array.Copy(streamForProto.ToArray(), 0, sendBuffer, HEAD_SIZE * HEAD_NUM, streamForProto.Length); lock (_socket) { if (_socket != null && _socket.Connected) { _socket.BeginSend(sendBuffer, 0, bufferSize, SocketFlags.None, new AsyncCallback(EndSendPacket), null); } } streamForProto.Dispose(); } catch (ObjectDisposedException) { Log4U.LogInfo("Send Closed"); } catch (Exception ex) { Log4U.LogError(ex.Message); } }
private void BeginReceivePacket() { try { lock (_socket) { _socket.BeginReceive(_receiveBuffer, 0, _socket.ReceiveBufferSize, SocketFlags.None, new AsyncCallback(EndReceivePacket), null); } } catch (Exception ex) { Log4U.LogError(ex.Message); } }
private void EndSendPacket(IAsyncResult ar) { //int bytesSend = 0; try { lock (_socket) { _socket.EndSend(ar); } } catch (Exception ex) { Log4U.LogError(ex.Message); } }
public void SetImage(Image image, EAtlasName eAtlasName, string spriteName) { GameObject go = Resources.Load <GameObject>("Raw/Image/" + _atlasPathDict[eAtlasName] + "/" + spriteName); if (go != null) { try { Sprite sprite = go.GetComponent <SpriteRenderer>().sprite; image.sprite = sprite; }catch (System.NullReferenceException) { Log4U.LogError(eAtlasName, spriteName); } } }
public static T DeserializeFromFile <T>(string filePath) where T : global::ProtoBuf.IExtensible { T item = default(T); using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read)) { try { item = Serializer.Deserialize <T>(fs); }catch (Exception ex) { Log4U.LogError(ex); } } return(item); }
private void DoBeginSendPacket(ENetworkMessage networkMessage, byte[] msgID) { try { byte[] sendBuffer = new byte[HEAD_SIZE * HEAD_NUM]; byte[] bufferSizeBytes = MiniConverter.IntToBytes(HEAD_SIZE * HEAD_NUM); byte[] networkMessageBytes = MiniConverter.IntToBytes((int)networkMessage); Array.Copy(bufferSizeBytes, 0, sendBuffer, HEAD_SIZE * 0, HEAD_SIZE); Array.Copy(networkMessageBytes, 0, sendBuffer, HEAD_SIZE * 1, HEAD_SIZE); Array.Copy(msgID, 0, sendBuffer, HEAD_SIZE * 2, HEAD_SIZE); lock (_socket) { _socket.BeginSend(sendBuffer, 0, HEAD_SIZE * HEAD_NUM, SocketFlags.None, new AsyncCallback(EndSendPacket), null); } } catch (Exception ex) { Log4U.LogError(ex.Message); } }
private IEnumerator BeginConnection() { try { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _socket.BeginConnect(GlobalVars.IPAddress, GlobalVars.IPPort, new AsyncCallback(FinishConnection), null); } catch (Exception ex) { Log4U.LogError(ex.StackTrace); yield break; } yield return(new WaitForSeconds(CONNECT_TIME_OUT)); if (_socket.Connected == false) { Log4U.LogInfo("Client Connect Time Out..."); CloseConnection(); } _isKeepAlive = _socket.Connected; }
private void EndReceivePacket(IAsyncResult ar) { int bytesRead = -1; try { if (IsConncted) { lock (_socket) { bytesRead = _socket.EndReceive(ar); } } if (bytesRead == -1) { CloseConnection(); return; } } catch (ObjectDisposedException) { Log4U.LogInfo("Receive Closed"); } catch (Exception ex) { Log4U.LogError(ex.Message + "\n " + ex.StackTrace + "\n" + ex.Source); } // Begin Read // int position = 0; while (position < bytesRead) { int bufferSize = MiniConverter.BytesToInt(_receiveBuffer, position + HEAD_SIZE * 0); ENetworkMessage networkMessage = (ENetworkMessage)MiniConverter.BytesToInt(_receiveBuffer, position + HEAD_SIZE * 1); byte[] msgIDBytes = new byte[HEAD_SIZE]; for (int i = 0; i < HEAD_SIZE; i++) { msgIDBytes[i] = _receiveBuffer[position + HEAD_SIZE * 2 + i]; } string msgID = BitConverter.ToString(msgIDBytes); if (networkMessage != ENetworkMessage.KEEP_ALIVE_SYNC) { Log4U.LogInfo("networkMessage : " + networkMessage, "msgID : " + msgID, "bufferSize : " + bufferSize); } if (position + bufferSize > bytesRead) { Log4U.LogError("Error receive packet, packet is too long : " + bufferSize); break; } IExtensible rspPacket = UnPackTool.UnPack(networkMessage, position + HEAD_SIZE * HEAD_NUM, bufferSize - HEAD_NUM * HEAD_SIZE, _receiveBuffer); if (rspPacket == null) { continue; } MessageArgs args = new MessageArgs { iMessageType = (uint)networkMessage, kParam = rspPacket, }; NetworkMessageParam networkParam = new NetworkMessageParam { rsp = rspPacket, msgID = msgID, }; lock (_msgIDDict) { if (_msgIDDict.ContainsKey(msgID)) { networkParam.req = _msgIDDict[msgID]; } if (_needReqMessageType.Contains(networkMessage)) { args.kParam = networkParam; } if (_forcePushMessageType.Contains(networkMessage) || _msgIDDict.ContainsKey(msgID)) { MessageDispatcher.GetInstance().DispatchMessageAsync(args.iMessageType, args.kParam); } if (_msgIDDict.ContainsKey(msgID)) { RemoveMsgID(msgID); } } //if (_forcePushMessageType.Contains(networkMessage)) //{ // DoBeginSendPacket(networkMessage, msgIDBytes); //} position += bufferSize; } Array.Clear(_receiveBuffer, 0, _socket.ReceiveBufferSize); BeginReceivePacket(); }
public static IExtensible UnPack(ENetworkMessage networkMessage, int startIndex, int length, byte[] buffer) { IExtensible packet = null; try { using (MemoryStream streamForProto = new MemoryStream(buffer, startIndex, length)) { switch (networkMessage) { case ENetworkMessage.KEEP_ALIVE_SYNC: packet = Serializer.Deserialize <KeepAliveSyncPacket>(streamForProto); break; case ENetworkMessage.REGISTER_RSP: packet = Serializer.Deserialize <RegisterRsp>(streamForProto); break; case ENetworkMessage.LOGIN_RSP: packet = Serializer.Deserialize <LoginRsp>(streamForProto); break; case ENetworkMessage.GET_USERINFO_RSP: packet = Serializer.Deserialize <GetUserInfoRsp>(streamForProto); break; case ENetworkMessage.PERSONALSETTINGS_RSP: packet = Serializer.Deserialize <PersonalSettingsRsp>(streamForProto); break; case ENetworkMessage.LOGOUT_RSP: packet = Serializer.Deserialize <LogoutRsp>(streamForProto); break; case ENetworkMessage.ADD_FRIEND_RSP: packet = Serializer.Deserialize <AddFriendRsp>(streamForProto); break; case ENetworkMessage.DELETE_FRIEND_RSP: packet = Serializer.Deserialize <DeleteFriendRsp>(streamForProto); break; case ENetworkMessage.OFFLINE_SYNC: packet = Serializer.Deserialize <OffLineSync>(streamForProto); break; case ENetworkMessage.GET_PERSONALINFO_RSP: packet = Serializer.Deserialize <GetPersonalInfoRsp>(streamForProto); break; case ENetworkMessage.CHANGE_FRIEND_SYNC: packet = Serializer.Deserialize <ChangeFriendSync>(streamForProto); break; case ENetworkMessage.SEND_CHAT_RSP: packet = Serializer.Deserialize <SendChatRsp>(streamForProto); break; case ENetworkMessage.RECEIVE_CHAT_SYNC: packet = Serializer.Deserialize <ReceiveChatSync>(streamForProto); break; case ENetworkMessage.CREATE_GROUP_CHAT_RSP: packet = Serializer.Deserialize <CreateGroupChatRsp>(streamForProto); break; case ENetworkMessage.CHANGE_GROUP_SYNC: packet = Serializer.Deserialize <ChangeGroupSync>(streamForProto); break; case ENetworkMessage.CHANGE_GROUP_RSP: packet = Serializer.Deserialize <ChangeGroupRsp>(streamForProto); break; case ENetworkMessage.GET_GROUP_INFO_RSP: packet = Serializer.Deserialize <GetGroupInfoRsp>(streamForProto); break; default: Log4U.LogInfo("No Such Packet, packet type is " + networkMessage); break; } } } catch (System.Exception ex) { Log4U.LogError(ex.Message + "\n " + ex.StackTrace + "\n" + ex.Source); } return(packet); }