zoukankan      html  css  js  c++  java
  • 获得WCF Client端的本地端口

    获得WCF Client端的本地端口

      最近需要做个小功能,当WCF调用远程服务时,显示该调用的网速或流量。其中比较关键的一步就是需要获得WCF  Client端的本地端口,原来以为是个简单的事情,结果查了1个多小时谷歌,硬是没找到好的法子,只有自己动手了。

        首先,反编译System.ServiceModel.dll的代码,查找Socket,然后,就是一直反复的“转到定义”、“查找所有引用",最后利用反射搞定了!代码分享如下,如果大家有什么更好的方法,请告知下。

    复制代码
                var temp = RASHelper.CreatProxy<IFileUpLoadService>(SystemConfiger.ServerEndPoint);//创建ClientProxy,就是调用ChannelFactory<T>.CreateChannel方法。
                (temp as ICommunicationObject).Open();//打开连接,需要该操作内部才会创建Socket对象,并调用Connect方法。
                var realProxy= System.Runtime.Remoting.RemotingServices.GetRealProxy(temp);//RealProxy,获得真实代理
                var channel = GetField(realProxy, "serviceChannel"); //ServiceChannel;
                var binder = GetField(channel, "binder");//binder;
                var binderChannel = GetField(binder, "channel");//binderChannel
                var connetion = GetProperty(binderChannel, "Connection");//IConnect
                var innerConnetion = GetProperty(connetion, "Connection");//InnerIConnect;
                Socket socket = GetField(innerConnetion, "socket") as Socket;//曙光初现
                var localPort = socket.LocalEndPoint;//千辛万苦,拿到本地端口;
                Console.Write(localPort);
            }
    
            private static object GetField(object obj, string fieled)
            {
               return obj.GetType().GetField(fieled, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
            }
    
            private static object GetProperty(object obj, string fieled)
            {
                return obj.GetType().GetProperty(fieled, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj,null);
            }
    复制代码
     
     
     
  • 相关阅读:
    remove white space from read
    optimize the access speed of django website
    dowload image from requests
    run jupyter from command
    crawl wechat page
    python version 2.7 required which was not found in the registry windows 7
    health
    alternate rows shading using conditional formatting
    word
    【JAVA基础】static 关键字
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3605738.html
Copyright © 2011-2022 走看看