public void FlushMsg(object state)
        {
            if (!flushMsgThreadSignal.WaitOne(5))
            {
                return;
            }

            flushMsgThreadSignal.Reset();

            try
            {
                TBase msg = null;
                using (var serializer = new HeaderTBaseSerializer())
                {
                    while (cachedQueue.TryDequeue(out msg))
                    {
                        var data = serializer.serialize(msg);
                        server.SendTo(data, ipep);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Logger.Current.Error(ex.ToString());
            }

            flushMsgThreadSignal.Set();
        }
 public void Send(TBase @base)
 {
     if (@base != null)
     {
         cachedQueue.Enqueue(@base);
     }
 }
Ejemplo n.º 3
0
	void SendMessageToClient(JStateObject state, byte messageType, TBase message)
	{
		int length = JThrift.Serialize(messageType, message, ref state.writeBuffer);
		server.Send(state.workSocket, state.writeBuffer, length);

		Debug.Log(string.Format("<color=green>R: ->C ({0}) - {1} </color> \n", state.name, message));
	}
Ejemplo n.º 4
0
 public void putMsg(TBase tBase)
 {
     if (tBase is LogEvent)
     {
         this.chunk.LogEvents.Add((LogEvent)tBase);
         this.chunkSize++;
         return;
     }
     else if (tBase is  MetricEvent)
     {
         this.chunk.Metrics.Add((MetricEvent)tBase);
         this.chunkSize++;
         return;
     }
     else if (tBase is  Span)
     {
         this.chunk.Spans.Add((Span)tBase);
         this.chunkSize++;
         return;
     }
     else if (tBase is Event)
     {
         this.chunk.Events.Add((Event)tBase);
         this.chunkSize++;
         return;
     }
 }
Ejemplo n.º 5
0
 public void DeSerialize(TBase tbase, byte[] bytes)
 {
     if (tbase == null || bytes == null)
     {
         return;
     }
     DeSerialize(tbase, bytes, 0, bytes.Length);
 }
Ejemplo n.º 6
0
        // from: https://stackoverflow.com/questions/24988527/tserializer-serializer-new-tserializer-in-c-sharp
        private byte[] Serialize(TBase obj)
        {
            var       stream    = new MemoryStream();
            TProtocol tProtocol = new TBinaryProtocol(new TStreamTransport(stream, stream));

            obj.Write(tProtocol);
            return(stream.ToArray());
        }
Ejemplo n.º 7
0
 public void SendMsgToServer(TBase msgValue)
 {
     if (CheckSocketStatus())
     {
         PingTickTask.ResetSendMsgTime();
         m_BufferTool.EncodeGamePackage(msgValue);
         Send(msgValue);
     }
 }
Ejemplo n.º 8
0
 private void Send(TBase msgValue)
 {
     if (m_Status == SocketStatus.Idle || m_Status == SocketStatus.Closing)
     {
         return;
     }
     m_Status = SocketStatus.Sending;
     m_Socket.BeginSend(m_BufferTool.GetSendBuffer(), 0, m_BufferTool.GetSendBufferSize(), 0, SendEventHandle, msgValue);
 }
Ejemplo n.º 9
0
        public static int GetMessageId(TBase message)
        {
            if (CanSupportMessage(message))
            {
                return(REQ_MSG_ID[message.GetType()]);
            }

            return(-1);
        }
        public static int GetMessageId(TBase message)
        {
            if (CanSupportMessage(message))
            {
                return REQ_MSG_ID[message.GetType()];
            }

            return -1;
        }
Ejemplo n.º 11
0
 public PendingInjection(TBase targetModel, Inject inject, Type modelType, Type iface = null,
                         TBase single = null)
 {
     TargetModel = targetModel;
     Injection   = inject;
     ModelType   = modelType;
     Interface   = iface;
     Single      = single;
 }
        public byte[] serialize(TBase @base)
        {
            var header = locator.HeaderLookup(@base);

            Reset();
            WriteHeader(header);
            @base.Write(protocol);
            return(baos.ToArray());
        }
Ejemplo n.º 13
0
        public RoutineInstanceBuilder AddParameter(String name, String dataTypeId, TBase value)
        {
            ResourceDTO resource = new ResourceDTO();

            resource.DataTypeId = dataTypeId;
            resource.Data       = Serialize(value);
            inParams.Add(name, resource);
            return(this);
        }
Ejemplo n.º 14
0
        public static byte[] Serialize(TBase s)
        {
            var t = new TMemoryBuffer();
            var p = new TBinaryProtocol(t);

            s.Write(p);

            return(t.GetBuffer());
        }
Ejemplo n.º 15
0
    public void CopyClass(TBase src, TBase tar)
    {
        if (src == null || tar == null)
        {
            return;
        }

        byte[] data = Serialize(src);
        DeSerialize(tar, data);
    }
Ejemplo n.º 16
0
            /// <summary>
            /// Perform the injection
            /// </summary>
            /// <returns>What was injected</returns>
            public TBase Inject(TBase model, Type iface = null, TBase single = null)
            {
                model.Registry = _reg;
                foreach (var inject in _injections)
                {
                    _reg.Inject(model, inject, iface, single);
                }

                return(model);
            }
Ejemplo n.º 17
0
 public static T Deserialize <T>(byte[] buffer) where T : new()
 {
     using (TMemoryBuffer trans = new TMemoryBuffer(buffer))
     {
         TProtocol proto        = new TCompactProtocol(trans);
         TBase     deserialized = (TBase) new T();
         deserialized.Read(proto);
         return((T)deserialized);
     }
 }
Ejemplo n.º 18
0
 /// <summary>
 /// CalcSizeOfSerializedThrift calculates the size in bytes that a Thrift object will take up.
 /// </summary>
 /// <param name="thriftBase">the base Thrift object to calculate the size of</param>
 /// <returns></returns>
 private async Task <int> CalcSizeOfSerializedThrift(TBase thriftBase)
 {
     _thriftBuffer.Reset();
     try {
         await thriftBase.WriteAsync(_thriftProtocol, CancellationToken.None);
     } catch (Exception e) {
         throw new Exception("failed to calculate the size of a serialized thrift object", e);
     }
     return(_thriftBuffer.GetBuffer().Length);
 }
Ejemplo n.º 19
0
        bool Receive()
        {
            try
            {
                var msg = socket?.ReceiveMultipartMessage();
                if (msg == null || PubsubUtil.IsStoppingMessage(msg))
                {
                    PublisherLogger.Info("subscribe client stopped by stpping message!");
                    return(false);
                }

                var topic   = msg[0].ConvertToString();
                var msgType = msg[1].ConvertToString();
                if (MsgHandlers.TryGetValue(msgType, out Delegate mh))
                {
                    var respBytes = msg[2].Buffer;
                    var stream    = new MemoryStream(respBytes, 0, respBytes.Length);
                    using (TStreamTransport trans = new TStreamTransport(stream, stream))
                        using (TBinaryProtocol proto = new TBinaryProtocol(trans))
                        {
                            Type t = GeneratedTypeCache.GetType(msgType);
                            if (t == null)
                            {
                                throw new TargetInvocationException(new Exception($"can't get type for: {msgType}"));
                            }
                            TBase ret = Activator.CreateInstance(t) as TBase;
                            ret.Read(proto);
                            mh.DynamicInvoke(topic, ret);
                        }
                }
                return(true);
            }
            catch (Exception e)
            {
                if (e is TargetInvocationException)
                {
                    var ee = e as TargetInvocationException;
                    Log($"SubscribeClient, invoke exception: {(ee).InnerException.Message} \n {ee.InnerException.StackTrace}", Logging.LogLevel.Warn);
                    return(true);
                }
                if (e is TerminatingException)
                {
                    Log($"SubscribeClient, terminated: {e.Message}", Logging.LogLevel.Info);
                    return(false);
                }
                else
                {
                    Log(disposing ? $"SubscribeClient, disposing exception: {e.Message}" : $"subscribe client receive exception: {e.Message} \n {e.StackTrace}",
                        disposing ? Logging.LogLevel.Info : Logging.LogLevel.Error
                        );
                    return(false);
                }
            }
        }
        public static GameMessage CreateGameMessage(MessageType inType, TBase content, string inNetworkId)
        {
            GameMessage msg = new GameMessage
            {
                EventType = inType,
                Content   = Serialize(content),
                NetworkId = inNetworkId
            };

            return(msg);
        }
Ejemplo n.º 21
0
	public static long Serialize(TBase message, ref byte[] buffer, int offset)
	{
		MemoryStream outputStream = new MemoryStream(buffer, offset, buffer.Length - offset);
		
		TStreamTransport transport = new TStreamTransport(null, outputStream);
		TBinaryProtocol binaryProtocol = new TBinaryProtocol(transport);
		
		message.Write(binaryProtocol);
		
		return outputStream.Position;
	}
Ejemplo n.º 22
0
 public Base ConvertToClassBase(TBase pbase)
 {
     return(new Base
     {
         Nombre = pbase.Nombre,
         Departamento = pbase.Departamento,
         Ciudad = pbase.Ciudad,
         Direccion = pbase.Direccion,
         NumeroTelefono = pbase.NumeroTelefono
     });
 }
Ejemplo n.º 23
0
 public static byte[] SerializeGetBytes(object value)
 {
     using (TMemoryBuffer trans = new TMemoryBuffer())
     {
         TProtocol proto = new TCompactProtocol(trans);
         TBase     trade = (TBase)value;
         trade.Write(proto);
         byte[] bytes = trans.GetBuffer();
         return(bytes);
     }
 }
Ejemplo n.º 24
0
	void NotifyMessageToAllClients(byte messageType, TBase message)
	{
		//int length = JThrift.Serialize(messageType, message, ref writeBuffer);
		Debug.Log(string.Format("<color=green>R: ->All_C ({0}) - {1} </color> \n", messageType, message));

		foreach (JStateObject state in states)
		{
			//System.Buffer.BlockCopy(writeBuffer, 0, state.writeBuffer, 0, length);
			int length = JThrift.Serialize(messageType, message, ref state.writeBuffer);
			server.Send(state.workSocket, state.writeBuffer, length);
		}
	}
        public TBase Deserialize(byte[] buffer)
        {
            Reset();
            baos.Write(buffer, 0, buffer.Length);
            baos.Seek(0, SeekOrigin.Begin);
            baos = new MemoryStream(buffer);
            Header header = ReadHeader();
            TBase  @base  = locator.TBaseLookup(header.Type);

            @base.Read(protocol);
            return(@base);
        }
Ejemplo n.º 26
0
 public static Stream Serialize(object value)
 {
     using (TMemoryBuffer trans = new TMemoryBuffer())
     {
         TProtocol proto = new TCompactProtocol(trans);
         TBase     trade = (TBase)value;
         trade.Write(proto);
         byte[] bytes        = trans.GetBuffer();
         var    memoryStream = new MemoryStream(bytes);
         return(memoryStream);
     }
 }
Ejemplo n.º 27
0
 public Base ConvertToDomain(TBase b)
 {
     return(new Base
     {
         IdBase = b.IdBase,
         Nombre = b.Nombre,
         Region = b.Region,
         Ciudad = b.Ciudad,
         Direccion = b.Direccion,
         NumeroTelefono = b.NumeroTelefono
     });
 }
Ejemplo n.º 28
0
        public Header HeaderLookup(TBase tbase)
        {
            if (tbase == null)
            {
                throw new Exception("tbase must not be null");
            }
            if (tbase is TSpan)
            {
                return(SPAN_HEADER);
            }
            if (tbase is TSpanChunk)
            {
                return(SPANCHUNK_HEADER);
            }
            if (tbase is TSpanEvent)
            {
                return(SPANEVENT_HEADER);
            }
            if (tbase is TAgentInfo)
            {
                return(AGENT_INFO_HEADER);
            }
            if (tbase is TAgentStat)
            {
                return(AGENT_STAT_HEADER);
            }
            if (tbase is TAgentStatBatch)
            {
                return(AGENT_STAT_BATCH_HEADER);
            }
            if (tbase is TSqlMetaData)
            {
                return(SQLMETADATA_HEADER);
            }
            if (tbase is TApiMetaData)
            {
                return(APIMETADATA_HEADER);
            }
            if (tbase is TResult)
            {
                return(RESULT_HEADER);
            }
            if (tbase is TStringMetaData)
            {
                return(STRINGMETADATA_HEADER);
            }
            //if (tbase is NetworkAvailabilityCheckPacket) {
            //    return NETWORK_CHECK_HEADER;
            //}

            throw new TException("Unsupported Type" + tbase.GetType());
        }
Ejemplo n.º 29
0
	public static int Serialize(byte messageType, TBase message, ref byte[] buffer)
	{
		long thriftLength = JThrift.Serialize(message, ref buffer, 4);

		short totalLength = (short) (thriftLength + 4);
		byte[] lengthBytes = System.BitConverter.GetBytes(totalLength);

		buffer[0] = lengthBytes[0];
		buffer[1] = lengthBytes[1];
		buffer[2] = (byte)messageType;

		return totalLength;
	}
Ejemplo n.º 30
0
 /// <summary>
 /// serialize thrift msg to string
 /// </summary>
 /// <param name="tbase"></param>
 /// <returns></returns>
 public static string SerializeToBase64String(TBase tbase)
 {
     string szMsg = null;
     try
     {
         byte[] _bytes = Serialize(tbase);
         szMsg = Convert.ToBase64String(_bytes);
     }
     catch (Exception e)
     {
         Logger.LogError("SerializeToBase64String is exception, error : " + e.ToString());
     }
     return szMsg;
 }
Ejemplo n.º 31
0
        private ResponseMessage Decode(Stream responseStream)
        {
            ByteBuffer buffer = ByteBuffer.Allocate(512);

            byte[] tempBytes = new byte[256];
            while (true)
            {
                int readLen = responseStream.Read(tempBytes, 0, tempBytes.Length);
                if (readLen <= 0)
                {
                    break;
                }
                buffer.WriteBytes(tempBytes);
            }

            ResponseMessage responseMessage = new ResponseMessage();

            responseMessage.MessageId  = buffer.ReadInt();
            responseMessage.StatusCode = HttpStatusCode.OK;

            TBase message = ThriftMessageHelper.GetResponseMessage(responseMessage.MessageId);

            if (message == null)
            {
                Debuger.LogError("don't support response messageId:" + responseMessage.MessageId);
                return(null);
            }

            byte[] headerBytes = new byte[buffer.ReadInt()];
            buffer.ReadBytes(headerBytes, 0, headerBytes.Length);

            byte[] messageBytes = new byte[buffer.ReadInt()];
            buffer.ReadBytes(messageBytes, 0, messageBytes.Length);

            byte[] eventListBytes = new byte[buffer.ReadInt()];
            buffer.ReadBytes(eventListBytes, 0, eventListBytes.Length);

            responseMessage.Header = new Header();
            ThriftSerialize.DeSerialize(responseMessage.Header, headerBytes);

            responseMessage.Message = message;
            ThriftSerialize.DeSerialize(message, messageBytes);

            responseMessage.EventList = new MEventList();
            ThriftSerialize.DeSerialize(responseMessage.EventList, eventListBytes);


            return(responseMessage);
        }
Ejemplo n.º 32
0
 public static void DeSerialize(TBase tbase, byte[] bytes)
 {
     if (tbase == null || bytes == null)
     {
         return;
     }
     using (Stream inputStream = new MemoryStream(64))
     {
         inputStream.Write(bytes, 0, bytes.Length);
         inputStream.Position = 0;
         TStreamTransport transport = new TStreamTransport(inputStream, null);
         TProtocol protocol = new TCompactProtocol(transport);
         tbase.Read(protocol);
     }
 }
Ejemplo n.º 33
0
        /// <summary>
        /// serialize thrift msg object to byte array
        /// </summary>
        /// <param name="tbase"></param>
        /// <returns></returns>
        public static byte[] Serialize(TBase tbase)
        {
            if (tbase == null)
            {
                return null;
            }
            OUTPUT_STREAM.Seek(0, SeekOrigin.Begin);
            OUTPUT_STREAM.SetLength(0);

            tbase.Write(SERIALIZE_PROTOCOL);
			byte[] bytes = new byte[OUTPUT_STREAM.Length];
            OUTPUT_STREAM.Position = 0;
            OUTPUT_STREAM.Read(bytes, 0, bytes.Length);
            return bytes;
        }
Ejemplo n.º 34
0
 public void TrySetConfig(string path, TBase value)
 {
     if (m_ConfigPool.ContainsKey(path))
     {
         m_ConfigPool[path] = value;
     }
     else
     {
         m_ConfigPool.Add(path, value);
     }
     //save to file
     FileUtils.EnsureFolder(GetConfigPath() + path);
     byte[] buffer = ThriftSerialize.Serialize(value);
     FileUtils.WriteByteFile(GetConfigPath() + path, buffer);
 }
        public static byte[] SerializeCompact(TBase tbase)
        {
            if (tbase == null)
            {
                return(null);
            }

            using (MemoryStream outputStream = new MemoryStream())
            {
                TStreamTransport transport = new TStreamTransport(null, outputStream);
                TProtocol        protocol  = new TCompactProtocol(transport);
                tbase.Write(protocol);
                return(outputStream.ToArray());
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// deSerialize msg data to thrift msg object
        /// </summary>
        /// <param name="tbase"></param>
        /// <param name="bytes"></param>
        public static void DeSerialize(TBase tbase, byte[] bytes)
        {
            if (tbase == null || bytes == null)
            {
                return;
            }

            INPUT_STREAM.Seek(0, SeekOrigin.Begin);
            INPUT_STREAM.SetLength(0);

            INPUT_STREAM.Write(bytes, 0, bytes.Length);
            INPUT_STREAM.Seek(0, SeekOrigin.Begin);

            tbase.Read(DESERIALIZE_PROTOCOL);
        }
        public static string Serialize(TBase tbase)
        {
            if (tbase == null)
            {
                return(null);
            }

            using (MemoryStream outputStream = new MemoryStream())
            {
                TStreamTransport transport = new TStreamTransport(null, outputStream);
                TProtocol        protocol  = new TJSONProtocol(transport);
                tbase.Write(protocol);
                return(Encoding.UTF8.GetString(outputStream.ToArray()));
            }
        }
Ejemplo n.º 38
0
 public static void DeSerialize(TBase tbase, byte[] bytes)
 {
     if (tbase == null || bytes == null)
     {
         return;
     }
     using (Stream inputStream = new MemoryStream(64))
     {
         inputStream.Write(bytes, 0, bytes.Length);
         inputStream.Position = 0;
         TStreamTransport transport = new TStreamTransport(inputStream, null);
         TProtocol        protocol  = new TJSONProtocol(transport);
         tbase.Read(protocol);
     }
 }
Ejemplo n.º 39
0
    public T TryGetConfig <T>(string path) where T : class, TBase, new()
    {
        TBase config = null;

        if (m_ConfigPool.TryGetValue(path, out config))
        {
            return(config as T);
        }
        T configInstance = default(T);

        if (ResourceManager.DecodePersonalDataTemplate <T>(GetConfigPath() + path, ref configInstance))
        {
            m_ConfigPool.Add(path, configInstance);
        }
        return(configInstance);
    }
Ejemplo n.º 40
0
 public static byte[] Serialize(TBase tbase)
 {
     if (tbase == null)
     {
         return null;
     }
     using (Stream outputStream = new MemoryStream(64))
     {
         TStreamTransport transport = new TStreamTransport(null, outputStream);
         TProtocol protocol = new TCompactProtocol(transport);
         tbase.Write(protocol);
         byte[] bytes = new byte[outputStream.Length];
         outputStream.Position = 0;
         outputStream.Read(bytes, 0, bytes.Length);
         return bytes;
     }
 }
Ejemplo n.º 41
0
    public static void SendMessage(TBase msg, bool playLoadingWait = true)
    {
        lock (CSMsgQueue.SyncRoot)
        {
            CSMsgQueue.Enqueue(msg);
            //Throw the message sended event.
            if (OnMessageSended != null)
            {
                OnMessageSended(playLoadingWait);
            }
        }

        if (MsgThread.ThreadState == ThreadState.Unstarted)
        {
            MsgThread.Start();
        }
    }
Ejemplo n.º 42
0
        protected override void ReadImpl()
        {
            try
            {
                var contentLen = GetMsgLength() - MinMsgLen;
                if (contentLen <= 0)
                {
                    return;
                }

                var contentBytes = ReadBytes(contentLen);
                ThriftMsgSerialize.DeSerialize(content, contentBytes);
            }
            catch (Exception ex)
            {
                content = null;
                Logger.LogError(ex.ToString());
            }
        }
 public static bool CanSupportMessage(TBase message)
 {
     return REQ_MSG_ID.ContainsKey(message.GetType());
 }
Ejemplo n.º 44
0
 public ThriftSCMessage(short msgType)
 {
     this.msgType = msgType;
     content = SCMessageHelper.createMessage(msgType);
 }
Ejemplo n.º 45
0
        /// <summary>
        /// send msg to server
        /// </summary>
        /// <param name="msgContent"></param>
        public void SendMessage(TBase msgContent)
        {
            var msg = new ThriftCSMessage(msgContent);
            var bytes = msg.Encode();
            if (bytes == null || bytes.Length <= 0)
            {
                Logger.LogError("send data is null or length is 0, msg type = " + msgContent.GetType().ToString());
                return;
            }

            // TODO Encrypt Message Data
            StartSendMsg(bytes);
        }
Ejemplo n.º 46
0
 public ThriftCSMessage(TBase content)
 {
     this.content = content;
 }
Ejemplo n.º 47
0
	public void Send(Socket socket, byte messageType, TBase message)
	{
		int length = JThrift.Serialize(messageType, message, ref writeBuffer);

		Send(socket, writeBuffer, length);
	}
Ejemplo n.º 48
0
        public void StartSendMsg(TBase msgContent)
        {
            if (null == socketClient || !socketClient.IsConnected())
                return;

            Logger.LogError("send msg at time " + DateTime.Now + " : " + msgContent);
            socketClient.SendMessage(msgContent);
        }
Ejemplo n.º 49
0
	void SendToAllPeers(byte messageType, TBase message)
	{
		foreach (KeyValuePair<int, JStateObject> state in peers)
		{
			int length = JThrift.Serialize(messageType, message, ref writeBuffer);
			Send(state.Value.workSocket, writeBuffer, length);
			break;
		}
	}
Ejemplo n.º 50
0
	void OnNtfMatch(TBase message)
	{
//		Debug.Log("VirtualPlayer.OnNtfMatch \n" + message.ToString());

		NtfMatch msg = message as NtfMatch;
		//Debug.Log(string.Format("{0} got a match. localId({1}), \n{2}", ansLogin.NickName, msg.LocalId, message.ToString()));

		nation = msg.LocalId == 0 ? JgNation.kCho : JgNation.kHan;
		localId = msg.LocalId;

		this.Invoke("SendSangcharim", 1f);
	}
	public void SendMessageToServer(JgC2S_Msgs messageType, TBase message)
	{
		if (transport.IsBound() == false) return;

		Debug.Log(string.Format("C({0}): ->S ({1}) - {2} \n", dbgUserName, messageType, message));

		int length = JThrift.Serialize((byte)messageType, message, ref writeBuffer);

		transport.Write(writeBuffer, length);
	}
	public void WriteToServer(JgC2S_Msgs messageType, TBase message, Action<TBase> callback)
	{
		if (transport.IsBound() == false) return;

		int messageIndex = (int)messageType;
		messageCallbacks[messageIndex] = callback;

		SendMessageToServer(messageType, message);
	}
Ejemplo n.º 53
0
 /// <summary>
 /// deserializ string msg data to thrift msg object
 /// </summary>
 /// <param name="tbase"></param>
 /// <param name="szMsg"></param>
 public static void DeSerializeFromBase64String(TBase tbase, string szMsg)
 {
     try
     {
         byte[] _bytes = Convert.FromBase64String(szMsg);
         DeSerialize(tbase, _bytes);
     }
     catch (Exception e)
     {
         Logger.LogError("DeSerializeFromBase64String is exception, error : " + e.ToString());
     }
 }
Ejemplo n.º 54
0
 public static void SaveData(TBase data, string savePath)
 {
     byte[] fileData = ThriftSerialize.Serialize(data);
     FileUtils.WriteByteFile(savePath,fileData);
 }
Ejemplo n.º 55
-1
	public static void Deserialize(byte[] buffer, TBase message)
	{
		MemoryStream inputStream = new MemoryStream(buffer);
		
		TStreamTransport transport = new TStreamTransport(inputStream, null);
		TBinaryProtocol binaryProtocol = new TBinaryProtocol(transport);

		message.Read(binaryProtocol);
	}