Пример #1
0
 public TMessage(string name, TMessageType type, int seqid)
     : this()
 {
     Name  = name;
     Type  = type;
     SeqID = seqid;
 }
Пример #2
0
 internal void ReportMessage(TMessageType aType, string aMessage)
 {
     if (MessageHandler != null)
     {
         MessageHandler(aType, aMessage, this);
     }
 }
Пример #3
0
 public TMessage(string name, TMessageType type, int seqid)
     : this()
 {
     Name = name;
     Type = type;
     SeqID = seqid;
 }
Пример #4
0
        public async Task WriteReadMessage_Test(Type protocolType, TMessageType messageType)
        {
            var expected = new TMessage(nameof(TMessage), messageType, 1);

            try
            {
                var tuple = GetProtocolInstance(protocolType);
                using (var stream = tuple.Item1)
                {
                    var protocol = tuple.Item2;

                    await protocol.WriteMessageBeginAsync(expected);

                    await protocol.WriteMessageEndAsync();

                    stream.Seek(0, SeekOrigin.Begin);

                    var actualMessage = await protocol.ReadMessageBeginAsync();

                    await protocol.ReadMessageEndAsync();

                    var result = _compareLogic.Compare(expected, actualMessage);
                    Assert.IsTrue(result.AreEqual, result.DifferencesString);
                }
            }
            catch (Exception e)
            {
                throw new Exception($"Exception during testing of protocol: {protocolType.FullName}", e);
            }
        }
Пример #5
0
 public TMessage(String name, TMessageType type, Int32 seqid)
     : this()
 {
     Name  = name;
     Type  = type;
     SeqID = seqid;
 }
Пример #6
0
		public TMessage(string name, TMessageType type, int seqid)
			: this()
		{
			this.name = name;
			this.type = type;
			seqID = seqid;
		}
Пример #7
0
 public TMessage(string name, TMessageType type, int seqid)
     : this()
 {
     this.name  = name;
     this.type  = type;
     this.seqID = seqid;
 }
 public TMessage(string name, TMessageType type, int seqid, string serviceName = "")
     : this()
 {
     this.name = name;
     this.type = type;
     this.seqID = seqid;
     this.serviceName = serviceName;
 }
Пример #9
0
 public TMessage(string name, TMessageType type, int seqid)
 {
     this = new TMessage()
     {
         name  = name,
         type  = type,
         seqID = seqid
     };
 }
Пример #10
0
 public TMessage(String name, TMessageType type, Int32 seqid)
 {
     this = new TMessage()
     {
         Name  = name,
         Type  = type,
         SeqID = seqid
     };
 }
Пример #11
0
 public Example(string docFilename, string docHeading, string className, string methodName, TMessageType exampleType, string mimeType)
 {
     DocFilename = docFilename;
     DocHeading  = docHeading;
     ClassName   = className;
     MethodName  = methodName;
     ExampleType = exampleType;
     MimeType    = mimeType;
     Content     = new Dictionary <TDataExchangeFormat, string>();
 }
Пример #12
0
 public Example(string docFilename, string docHeading, string className, string methodName, TMessageType exampleType, string mimeType)
 {
     DocFilename = docFilename;
     DocHeading = docHeading;
     ClassName = className;
     MethodName = methodName;
     ExampleType = exampleType;
     MimeType = mimeType;
     Content = new Dictionary<TDataExchangeFormat, string>();
 }
Пример #13
0
        private TMessageType CreateGameMsg <TMessageType>() where TMessageType : IGameMessage, new()
        {
            var gameMsg = new TMessageType
            {
                GameId          = this.GameId,
                ConcurencyStamp = ++concurencyStamp,
            };

            return(gameMsg);
        }
Пример #14
0
        public string GetExampleContent(Type classType, MethodInfo methodInfo, TMessageType exampleType, string mimeType, TDataExchangeFormat dataExchangeFormat)
        {
            string  content = null;
            Example example = GetExample(classType, methodInfo, exampleType, mimeType);

            if (example != null)
            {
                example.Content.TryGetValue(dataExchangeFormat, out content);
            }
            return(content);
        }
Пример #15
0
        public override TMessage ReadMessageBegin()
        {
            this.EnsureReader();
            this.Context.ReadBegin();
            this.stack.Push(new StructContext(this));

            TMessageType type = CommonUtils.ToEnum <TMessageType>(this.element.Attribute("type").Value);
            int          seq  = CommonUtils.ToInt32(this.element.Attribute("seq").Value);

            return(new TMessage(this.element.Name.LocalName, type, seq));
        }
Пример #16
0
        public override void WriteMessageBegin(TMessage tMessage)
        {
            TMessageType type = tMessage.Type;

            if (type != TMessageType.Call && type != TMessageType.Oneway)
            {
                base.WriteMessageBegin(tMessage);
                return;
            }
            base.WriteMessageBegin(new TMessage(string.Concat(this.ServiceName, TMultiplexedProtocol.SEPARATOR, tMessage.Name), tMessage.Type, tMessage.SeqID));
        }
Пример #17
0
 public TMessage(string name, TMessageType type, string msgID, short liveLife, string sender, string receiver, string senderQueueName, string receiverQueueName)
     : this()
 {
     this.name              = name;
     this.type              = type;
     this.msgID             = msgID;
     this.liveLife          = liveLife;
     this.sender            = sender;
     this.receiver          = receiver;
     this.senderQueueName   = senderQueueName;
     this.receiverQueueName = receiverQueueName;
 }
Пример #18
0
        public async Task WriteReadMessage_Test(Type protocolType, TMessageType messageType)
        {
            var expected = new TMessage(nameof(TMessage), messageType, 1);

            try
            {
                var tuple = GetProtocolInstance(protocolType);
                using (var stream = tuple.Item1)
                {
                    var protocol = tuple.Item2;

                    await protocol.WriteMessageBeginAsync(expected, default);

                    await protocol.WriteMessageEndAsync(default);
Пример #19
0
 public Example GetExample(Type classType, MethodInfo methodInfo, TMessageType exampleType, string mimeType)
 {
     if (mimeType.Contains("+"))
     {
         mimeType = mimeType.Substring(0, mimeType.IndexOf('+'));
     }
     Example example = null;
     string key = string.Concat(classType.Name, methodInfo.Name, exampleType, mimeType);
     _Examples.TryGetValue(key, out example);
     if (mimeType.Length > 0 && example == null)
     {
         example = GetExample(classType, methodInfo, exampleType, "");
     }
     return example;
 }
Пример #20
0
        public Example GetExample(Type classType, MethodInfo methodInfo, TMessageType exampleType, string mimeType)
        {
            if (mimeType.Contains("+"))
            {
                mimeType = mimeType.Substring(0, mimeType.IndexOf('+'));
            }
            Example example = null;
            string  key     = string.Concat(classType.Name, methodInfo.Name, exampleType, mimeType);

            _Examples.TryGetValue(key, out example);
            if (mimeType.Length > 0 && example == null)
            {
                example = GetExample(classType, methodInfo, exampleType, "");
            }
            return(example);
        }
Пример #21
0
        private void WriteResponse(TProtocol outProtocol,
                                   int sequenceId,
                                   TMessageType responseType,
                                   String responseFieldName,
                                   short responseFieldId,
                                   IThriftCodec responseCodec,
                                   Object result)
        {
            outProtocol.WriteMessageBegin(new TMessage(this.QualifiedName, responseType, sequenceId));

            TProtocolWriter writer = new TProtocolWriter(outProtocol);

            writer.WriteStructBegin(_resultStructName);
            writer.WriteField(responseFieldName, (short)responseFieldId, responseCodec, result);
            writer.WriteStructEnd();

            outProtocol.WriteMessageEnd();
            outProtocol.Transport.Flush();
        }
Пример #22
0
        public void ReadExamples(string baseDirectory, string filename, ResourceNode resourceTree)
        {
            Example             currentExample       = null;
            StringBuilder       currentExampleBody   = null;
            TDataExchangeFormat currentExampleFormat = TDataExchangeFormat.None;
            bool   inExample   = false;
            string lastHeading = null;
            bool   generateXml = true;

            foreach (string line in File.ReadLines(filename))
            {
                string trimmed = line.Trim();
                if (trimmed.StartsWith("#"))
                {
                    lastHeading = trimmed.Replace("#", "").Trim().Replace(" ", "-").ToLower();
                }
                else if (trimmed.StartsWith("[]: [!generateXml]"))
                {
                    generateXml = false;
                }
                if (trimmed.StartsWith("```"))
                {
                    if (currentExample != null)
                    {
                        string exampleFormat = trimmed.Substring("```".Length);
                        if (exampleFormat.Equals(TDataExchangeFormat.Json.ToString().ToLower()))
                        {
                            currentExampleFormat = TDataExchangeFormat.Json;
                            inExample            = true;
                        }
                        else if (exampleFormat.Equals(FORM_EXAMPLE))
                        {
                            currentExampleFormat = TDataExchangeFormat.FormUrlEncoded;
                            inExample            = true;
                        }
                        else if (inExample && exampleFormat.Length == 0)
                        {
                            if (currentExampleFormat == TDataExchangeFormat.FormUrlEncoded)
                            {
                                currentExample.Content.Add(currentExampleFormat, currentExampleBody.ToString());
                            }
                            else
                            {
                                currentExample.Content.Add(TDataExchangeFormat.Json, currentExampleBody.ToString());
                                if (generateXml)
                                {
                                    currentExample.Content.Add(TDataExchangeFormat.Xml, JsonToXml(currentExample, resourceTree, currentExampleBody.ToString()));
                                }
                            }
                            currentExample = null;
                            inExample      = false;
                            generateXml    = true;
                        }
                    }
                }
                else
                {
                    if (inExample)
                    {
                        if (line.Trim().Length > 0)
                        {
                            currentExampleBody.Append(line);// string.Concat(line, "\r\n"));
                        }
                    }
                    else
                    {
                        MatchCollection matches = EXAMPLE_NAME_REGEX.Matches(trimmed);
                        if (matches.Count == 1)
                        {
                            string   fullExampleName       = matches[0].Value;
                            string   prefix                = "[]: [";
                            string   suffix                = "]";
                            string   withoutSquareBrackets = fullExampleName.Substring(prefix.Length, matches[0].Value.Length - prefix.Length - suffix.Length);
                            string[] parts      = withoutSquareBrackets.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                            string   className  = parts[0];
                            string   methodName = parts[1];
                            string   mimeType   = trimmed.Substring(fullExampleName.Length);
                            if (mimeType.Length > 0)
                            {
                                if (mimeType.StartsWith("[") && mimeType.EndsWith("]"))
                                {
                                    mimeType = mimeType.Substring(1, mimeType.Length - 2);
                                }
                                else
                                {
                                    SerialisationLog.Warning(string.Concat("Invalid mimetype on example tag: ", trimmed, " in ", filename));
                                    mimeType = "";
                                }
                            }

                            if (resourceTree.Find(className, methodName) != null)
                            {
                                TMessageType messageType     = (TMessageType)Enum.Parse(typeof(TMessageType), parts[2]);
                                string       exampleFilename = filename.Substring(baseDirectory.Length);
                                currentExample     = new Example(exampleFilename, lastHeading, className, methodName, messageType, mimeType);
                                currentExampleBody = new StringBuilder();

                                string key = string.Concat(currentExample.ClassName, currentExample.MethodName, currentExample.ExampleType.ToString(), mimeType);
                                if (!_Examples.ContainsKey(key))
                                {
                                    _Examples.Add(key, currentExample);
                                }
                                else
                                {
                                    SerialisationLog.Error(string.Concat("An example already exists for ", currentExample.ClassName, ".", currentExample.MethodName, ".", currentExample.ExampleType.ToString(), "files: [", currentExample.DocFilename, ", ", _Examples[key].DocFilename, "]"));
                                }
                            }
                            else
                            {
                                SerialisationLog.Error(string.Concat("The method ", className, ".", methodName, " in ", filename, " does not exist"));
                            }
                        }
                    }
                }
            }
        }
 private void WriteBody(StreamWriter writer, ExampleStore exampleStore, ResourceNode node, TDataExchangeFormat dataExchangeFormat, string contentType, TMessageType messageType, Type bodyObjectType, int indent)
 {
     writer.WriteLine(string.Concat(GetIndentString(indent), contentType, ":"));
     if (SerialisationUtils.IsStandardDataExchangeFormat(dataExchangeFormat))
     {
         writer.WriteLine(string.Concat(GetIndentString(indent + 1), "schema: ", GetSchemaKey(bodyObjectType, dataExchangeFormat)));
     }
     WriteExample(writer, exampleStore, node.Class, node.Method, contentType, messageType, dataExchangeFormat, indent + 1);
 }
Пример #24
0
        /// <summary>
        /// 远程方法调用
        /// </summary>
        /// <param name="recvAddress">接收节点的虚拟IP地址,如3.1/param>
        /// <param name="interfaceName">接口名称</param>
        /// <param name="methodName">方法名称</param>
        /// <param name="paramDict">参数字段</param>
        /// <param name="liveLife">生命周期,以秒为单位</param>
        /// <param name="messageType">消息类型</param>
        /// <returns>服务端返回的数据或者null</returns>
        public object Call(string recvAddress, ushort destVPort, string interfaceName, string methodName, Dictionary <string, object> paramDict, short liveLife, TMessageType messageType = TMessageType.RpcCall)
        {
            object result = null;

            _msgID = _msgID < int.MaxValue ? ++_msgID : 0;

            try
            {
                VirtuaIP receiverVIP = new VirtuaIP(recvAddress);
                string   msgID       = _msgID.ToString();

                if (!InterfaceImplementMap.InterfaceAndImplementMap.ContainsKey(interfaceName))
                {
                    throw new ApplicationException("找不到接口" + interfaceName + "的具体实现!");
                }

                DynMethodInstance dynMethodInstance = new DynMethodInstance(interfaceName, methodName);
                TMessage          reqMsg            = new TMessage(interfaceName + "_" + methodName, messageType, msgID, liveLife, "", "", "", "");
                TSerializer       serializerReq     = new TBinarySerializer();
                //将消息头信息写入流
                serializerReq.WriteMessageBegin(reqMsg);
                foreach (var para in paramDict)
                {
                    dynMethodInstance[para.Key] = para.Value;
                }
                //将方法的实例写入流
                DynSerialize.WriteDynMethodInstance(serializerReq, dynMethodInstance);

                //什么都不做
                serializerReq.WriteMessageEnd();
                //将消息流转换成二进制流
                byte[] reqData = serializerReq.ToBytes();
                serializerReq.Flush();

                //发送消息
                Send(receiverVIP, destVPort, reqData);

                var timeout = new TimeSpan(0, 0, liveLife);
                //创建一个 Stopwatch 实例:使用 StartNew() 会创建一个 Stopwatch 实例并马上开始计时,即等效于如下代码:
                //Stopwatch sw2 = new Stopwatch();
                //sw2.Start();
                var  timer     = Stopwatch.StartNew();
                bool isReceive = false;

                do
                {
                    ZmqMessage zmqMessage = _reqSocket.ReceiveMessage(timeout - timer.Elapsed);
                    if (zmqMessage.FrameCount == 0)
                    {
                        throw new TimeoutException("调用超时,请检查网络是否联通!");
                    }
                    else
                    {
                        //zmqMessage[zmqMessage.FrameCount - 1].Buffer 只需要处理zmqMessage中最后一帧,这一帧存的是消息中的数据部分
                        result = DealRepMessage(zmqMessage[zmqMessage.FrameCount - 1].Buffer, msgID, out isReceive);

                        //消息ID不匹配且超时时间未到时,丢掉当前接收到的数据包,继续接受数据
                        if (isReceive)
                        {
                            return(result);
                        }
                    }
                }while (timer.Elapsed <= timeout);

                throw new TimeoutException("调用超时,请检查网络是否联通!");
            }
            catch (Exception ex)
            {
                this.RaiseDealMessageExceptionEvent(ex);
                throw;
            }
        }
        private void WriteExample(StreamWriter writer, ExampleStore exampleStore, Type classType, MethodInfo methodInfo, string contentType, TMessageType exampleType, TDataExchangeFormat dataExchangeFormat, int indent)
        {
            string exampleText = exampleStore.GetExampleContent(classType, methodInfo, exampleType, contentType, dataExchangeFormat);

            if (exampleText != null)
            {
                writer.WriteLine(string.Concat(GetIndentString(indent), "example: |"));
                List <string> lines = SerialisationUtils.SplitLines(exampleText);
                foreach (string line in lines)
                {
                    writer.WriteLine(string.Concat(GetIndentString(indent + 1), line));
                }
            }
            else if (dataExchangeFormat != TDataExchangeFormat.Xml)
            {
                SerialisationLog.Warning(string.Concat("No example for ", classType.Name, ".", methodInfo.Name, " ", dataExchangeFormat, " ", exampleType.ToString().ToLower()));
            }
        }
Пример #26
0
        /// <summary>
        /// 远程方法调用
        /// </summary>
        /// <param name="recvAddress">接收节点的虚拟IP地址,如3.1/param>
        /// <param name="interfaceName">接口名称</param>
        /// <param name="methodName">方法名称</param>
        /// <param name="paramDict">参数字段</param>
        /// <param name="messageType">消息类型</param>
        public void Call(string recvAddress, ushort destVPort, string interfaceName, string methodName, Dictionary <string, object> paramDict, TMessageType messageType = TMessageType.RpcCall)
        {
            try
            {
                VirtuaIP receiverVIP = new VirtuaIP(recvAddress);
                string   msgID       = Guid.NewGuid().ToString();

                if (!InterfaceImplementMap.InterfaceAndImplementMap.ContainsKey(interfaceName))
                {
                    throw new ApplicationException("找不到接口" + interfaceName + "的具体实现!!");
                }

                //本地应用端口随机获取,目标端口确定
                TMessage          reqMsg            = new TMessage(interfaceName + "_" + methodName, messageType, msgID, -1, "", "", "", "");
                DynMethodInstance dynMethodInstance = new DynMethodInstance(interfaceName, methodName);
                TSerializer       serializerReq     = new TBinarySerializer();

                serializerReq.WriteMessageBegin(reqMsg);
                foreach (var para in paramDict)
                {
                    dynMethodInstance[para.Key] = para.Value;
                }

                DynSerialize.WriteDynMethodInstance(serializerReq, dynMethodInstance);
                serializerReq.WriteMessageEnd();
                byte[] reqData = serializerReq.ToBytes();

                serializerReq.Flush();

                Send(receiverVIP, destVPort, reqData);
            }
            catch (Exception ex)
            {
                this.RaiseDealMessageExceptionEvent(ex);
                throw new ApplicationException(ex.Message);
            }
        }
Пример #27
0
 public string GetExampleContent(Type classType, MethodInfo methodInfo, TMessageType exampleType, string mimeType, TDataExchangeFormat dataExchangeFormat)
 {
     string content = null;
     Example example = GetExample(classType, methodInfo, exampleType, mimeType);
     if (example != null)
     {
         example.Content.TryGetValue(dataExchangeFormat, out content);
     }
     return content;
 }
 private void WriteExample(StreamWriter writer, ExampleStore exampleStore, Type classType, MethodInfo methodInfo, string contentType, TMessageType exampleType, TDataExchangeFormat dataExchangeFormat, int indent)
 {
     string exampleText = exampleStore.GetExampleContent(classType, methodInfo, exampleType, contentType, dataExchangeFormat);
     if (exampleText != null)
     {
         writer.WriteLine(string.Concat(GetIndentString(indent), "example: |"));
         List<string> lines = SerialisationUtils.SplitLines(exampleText);
         foreach (string line in lines)
         {
             writer.WriteLine(string.Concat(GetIndentString(indent + 1), line));
         }
     }
     else if (dataExchangeFormat != TDataExchangeFormat.Xml)
     {
         SerialisationLog.Warning(string.Concat("No example for ", classType.Name, ".", methodInfo.Name, " ", dataExchangeFormat, " ", exampleType.ToString().ToLower()));
     }
 }
Пример #29
0
    /// <summary>
    /// Publishes the event of type TMessageType to all subscribers
    /// </summary>
    /// <typeparam name="TMessageType">The message type (Payload), must inherit CompositeEvent</typeparam>
    public void Publish <TMessageType>() where TMessageType : BaseEventMessage <TMessageType>, new()
    {
        TMessageType message = Activator.CreateInstance <TMessageType>();

        this.Publish(message);
    }
 private void WriteBody(StreamWriter writer, ExampleStore exampleStore, ResourceNode node, TDataExchangeFormat dataExchangeFormat, string contentType, TMessageType messageType, Type bodyObjectType, int indent)
 {
     writer.WriteLine(string.Concat(GetIndentString(indent), contentType, ":"));
     if (SerialisationUtils.IsStandardDataExchangeFormat(dataExchangeFormat))
     {
         writer.WriteLine(string.Concat(GetIndentString(indent + 1), "schema: ", GetSchemaKey(bodyObjectType, dataExchangeFormat)));
     }
     WriteExample(writer, exampleStore, node.Class, node.Method, contentType, messageType, dataExchangeFormat, indent + 1);
 }