Esempio n. 1
0
    public bool Connect(string host, int port)
    {
        if (m_Socket != null)
        {
            return(false);
        }

        m_Host = host;
        m_Port = port;

        try
        {
            m_HostEndPoint = IPUtils.GetHostEndPoint(m_Host, m_Port);
            if (m_HostEndPoint == null)
            {
                Close();
                return(false);
            }

            m_IsRunning = true;
            m_Socket    = new KCPSocket(0, 1);
            m_Socket.AddReceiveListener(m_HostEndPoint, OnReceive);
        }
        catch (Exception e)
        {
            Close();
            return(false);
        }
        return(true);
    }
Esempio n. 2
0
        static async Task Main(string[] args)
        {
            var services = new ServiceCollection()
                           .AddLogging(x =>
            {
                x.ClearProviders();
                x.AddConsole();
            })
                           .BuildServiceProvider();

            var serviceDescriptor = new ServiceDiscoveryMessage()
            {
                IpAddress  = ByteString.CopyFrom(IPUtils.GetLocalIpAddress().GetAddressBytes()),
                Port       = 8765,
                ServerName = Environment.MachineName
            };

            var s = new Socket(new SocketInformation());

            var logger       = services.GetRequiredService <ILogger <PhoneRemoteServiceBroadcaster <IMessage> > >();
            var clientLogger = services.GetRequiredService <ILogger <PhoneRemoteClient <IMessage> > >();

            var rnd = new Random();

            var tcpClient = new PhoneRemoteClient <IMessage>(new ProtobufMessageSerializer(), true, clientLogger);
            var endpoint  = await tcpClient.DiscoverServerAsync <ServiceDiscoveryMessage>(CancellationToken.None);

            await tcpClient.ConnectAsync(new IPEndPoint(endpoint.Address, endpoint.Port), CancellationToken.None);

            while (true)
            {
                await tcpClient.SendAsync(new CursorAction { DX = rnd.Next(-100, 100), DY = rnd.Next(-100, 100) }, CancellationToken.None);
            }
        }
Esempio n. 3
0
 private string GetMessage(string name, Models.EmailInfo model)
 {
     return($"[{IPUtils.GetLocalIp()}]"
            + $"通过【{name}】邮件接口向【{model.Email}】发送邮件,"
            + $"标题: {model.Title},"
            + $"内容:{model.Body}");
 }
Esempio n. 4
0
        public void AddEvent(string strManagerName, string strMsg, int intType)
        {
            EventLogInfo eventLogInfo = new EventLogInfo();

            eventLogInfo.UserName  = strManagerName;
            eventLogInfo.EventType = intType;
            eventLogInfo.Lang      = JObject.cultureLang;
            string iP = IPUtils.GetIP();

            if (!string.IsNullOrEmpty(iP))
            {
                eventLogInfo.IPAddress = iP;
                if (intType.Equals(1))
                {
                    eventLogInfo.IPArea = IPUtils.GetIPAreaFromPcOnline(eventLogInfo.IPAddress);
                }
                else
                {
                    eventLogInfo.IPArea = string.Empty;
                }
            }
            else
            {
                eventLogInfo.IPAddress = "127.0.0.1";
                eventLogInfo.IPArea    = "未知地址或者获取地址失败";
            }
            eventLogInfo.EventInfo     = strMsg;
            eventLogInfo.AutoTimeStamp = DateTime.Now;
            EventLog.Add(eventLogInfo);
        }
Esempio n. 5
0
        public static bool IsIPDenyOrAllow(IList <IPStrategyInfo> listSource, string strLocalIP, IPStrategyType enuStrategyType)
        {
            bool result = false;

            foreach (IPStrategyInfo current in listSource)
            {
                if (current.Strategy == enuStrategyType.ToString())
                {
                    if (current.IPAddress.IndexOf("-") != -1)
                    {
                        string strBeginIP = current.IPAddress.Split(new char[]
                        {
                            '-'
                        })[0];
                        string strEndIP = current.IPAddress.Split(new char[]
                        {
                            '-'
                        })[1];
                        if (IPUtils.IsInIPDuan(strLocalIP, strBeginIP, strEndIP))
                        {
                            result = true;
                            break;
                        }
                    }
                    else if (current.IPAddress == strLocalIP)
                    {
                        result = true;
                        break;
                    }
                }
            }
            return(result);
        }
Esempio n. 6
0
        //=================================================================================
        //发送逻辑
        //=================================================================================
        private void SendMessage(int dst, byte[] bytes, int len)
        {
            int        dstPort = IPCConfig.GetIPCInfo(dst).port;
            IPEndPoint ep      = IPUtils.GetHostEndPoint("127.0.0.1", dstPort);

            m_SystemSocket.SendTo(bytes, 0, len, SocketFlags.None, ep);
        }
Esempio n. 7
0
        //=================================================================================
        #region 构造和析构

        public KCPSocket(int bindPort, uint kcpKey, AddressFamily family = AddressFamily.InterNetwork)
        {
            m_AddrFamily = family;
            m_KcpKey     = kcpKey;
            m_ListKcp    = new List <KCPProxy>();

            m_SystemSocket = new Socket(m_AddrFamily, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = IPUtils.GetIPEndPointAny(m_AddrFamily, bindPort);

            m_SystemSocket.Bind(ipep);

            bindPort = (m_SystemSocket.LocalEndPoint as IPEndPoint).Port;
            LOG_TAG  = "KCPSocket[" + bindPort + "-" + kcpKey + "]";

            m_IsRunning  = true;
            m_ThreadRecv = new Thread(Thread_Recv)
            {
                IsBackground = true
            };
            m_ThreadRecv.Start();



#if UNITY_EDITOR_WIN
            uint IOC_IN            = 0x80000000;
            uint IOC_VENDOR        = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
            m_SystemSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
#endif

#if UNITY_EDITOR
            UnityEditor.EditorApplication.playmodeStateChanged -= OnEditorPlayModeChanged;
            UnityEditor.EditorApplication.playmodeStateChanged += OnEditorPlayModeChanged;
#endif
        }
Esempio n. 8
0
        private static async void ActivityManager_OnActivityJoin(string secret)
        {
            if (Multiplayer.IsActive)
            {
                Log.Warn("Cannot join lobby from Discord, we are already in a lobby.");
                return;
            }

            if (string.IsNullOrWhiteSpace(secret))
            {
                Log.Warn("Received Discord invite without IP address.");
                return;
            }

            var ipAddresses = secret.FromBase64().Split(';');

            if (ipAddresses.Length != 1 && ipAddresses.Length != 3)
            {
                Log.Warn("Received invalid discord invite.");
                return;
            }

            string ipAddress = string.Empty;

            if (ipAddresses.Length == 1 && ipAddresses[0].Contains("ngrok"))
            {
                ipAddress = ipAddresses[0];
            }

            if (string.IsNullOrWhiteSpace(ipAddress) && await IPUtils.IsIPv6Supported())
            {
                if (ipAddresses.Length > 1)
                {
                    if (IPUtils.IsIPv6(ipAddresses[1]))
                    {
                        ipAddress = $"{ipAddresses[1]}:{ipAddresses[2]}";
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(ipAddress))
            {
                if (IPUtils.IsIPv4(ipAddresses[0]))
                {
                    ipAddress = $"{ipAddresses[0]}:{ipAddresses[2]}";
                }
            }

            if (string.IsNullOrWhiteSpace(ipAddress))
            {
                Log.Warn("Received Discord invite with invalid IP address.");
                return;
            }

            Log.Info("Joining lobby from Discord...");
            UIMainMenu_Patch.OnMultiplayerButtonClick();
            UIMainMenu_Patch.JoinGame($"{ipAddress}");
            DiscordManager.UpdateRichPresence(ip: secret, secretPassthrough: true, updateTimestamp: true);
        }
Esempio n. 9
0
    private void BroadcastIPAddress()
    {
        string ip = IPUtils.GetIpAddress();

        Debug.LogFormat("广播消息{0}", ip);
        byte[] buf = Encoding.Default.GetBytes(ip);
        udpServer.Broadcast(buf, udpPort);
    }
Esempio n. 10
0
 public ViewModel()
 {
     server = new CCC_Server();
     Clients = new ObservableCollection<string>();
     Port = 0;
     LocalAddress = IPUtils.GetLocalAddress(); ;
     PublicAddress = IPUtils.GetPublicAddress();
     startCommand = new RelayCommand(OnStartExecuted, OnStartCanExecute);
     stopCommand = new RelayCommand(OnStopExecuted, OnStopCanExecute);
 }
Esempio n. 11
0
        private string CreateConsumerNameByIP()
        {
            if (string.IsNullOrEmpty(IPValue))
            {
                IPValue = IPUtils.IPToInt(IPUtils.GetLocalIP()).ToString();
                AssertUtils.IsNotEmpty(IPValue, "获取本机IP地址错误");
            }

            return($"{RedisMessageBusOptions.DefaultConsumerName}_{IPValue}");
        }
        private void OnServerGUI()
        {
            EditorGUI.BeginChangeCheck();
            _socketPort = EditorGUILayout.IntField(new GUIContent("Socket Port", "The socket port used to host this server through."), _socketPort);

            if (EditorGUI.EndChangeCheck())
            {
                BuildScriptPrefs.SetSocketPort(_socketPort);
            }

            EditorGUILayout.Separator();

            var ip = IPUtils.GetLocalIPv4(NetworkInterfaceType.Ethernet);

            if (!string.IsNullOrEmpty(ip))
            {
                EditorGUILayout.DelayedTextField(new GUIContent("Ethernet IP v4 Address:", "Automatically identified local IP V4 address for Ethernet (Read Only)."), ip);
            }

            ip = IPUtils.GetLocalIPv4(NetworkInterfaceType.Wireless80211);
            if (!string.IsNullOrEmpty(ip))
            {
                EditorGUILayout.DelayedTextField(new GUIContent("Wireless IP v4 Address:", "Automatically identified local IP V4 address for Wireless (Read Only)."), ip);
            }

            EditorGUILayout.Separator();
            EditorGUILayout.BeginHorizontal();

            if (GUILayout.Button("Build for Server"))
            {
                if (!Directory.Exists(_buildFolder))
                {
                    SetBuildFolder();
                }

                if (_buildAndRun)
                {
                    BuildScripts.BuildAndRunServer64(_serverOnlyScene, _buildFolder, _devBuild, _buildTarget, _socketPort);
                }
                else
                {
                    BuildScripts.BuildServer64(_serverOnlyScene, _buildFolder, _devBuild, _buildTarget, _socketPort);
                }

                GUIUtility.ExitGUI();
            }

            if (GUILayout.Button("Run as Server"))
            {
                BuildScripts.PlayAsServer(_serverOnlyScene, _socketPort);
                GUIUtility.ExitGUI();
            }

            EditorGUILayout.EndHorizontal();
        }
Esempio n. 13
0
        private void AddComment()
        {
            int         formInt     = WebUtils.GetFormInt("cmtcontid", 0);
            ContentInfo contentById = Content.GetContentById(formInt);
            string      formString  = WebUtils.GetFormString("cmtusername");
            string      formString2 = WebUtils.GetFormString("cmtemail");
            string      formString3 = WebUtils.GetFormString("cmttitle");
            string      formString4 = WebUtils.GetFormString("cmtcontent");
            string      formString5 = WebUtils.GetFormString("ccode");

            if (base.ValidateCode != formString5)
            {
                base.Response.Write("验证码不正确");
            }
            else if (contentById == null)
            {
                base.Response.Write("没有找到相关内容");
            }
            else if (string.IsNullOrEmpty(formString))
            {
                base.Response.Write("用户名称不为空");
            }
            else if (string.IsNullOrEmpty(formString3))
            {
                base.Response.Write("标题不为空");
            }
            else if (string.IsNullOrEmpty(formString4))
            {
                base.Response.Write("评论内容不为空");
            }
            else if (Comment.Add(new CommentInfo
            {
                Content = formString4,
                ContID = contentById.AutoID,
                ContName = contentById.Title,
                EnableAnonymous = true,
                IPAddress = IPUtils.GetIP(),
                IPArea = string.Empty,
                IsAudit = true,
                IsReply = false,
                Lang = base.cultureLang,
                ReplyID = 0,
                Title = formString3,
                UserID = 0,
                UserName = formString,
                AutoTimeStamp = System.DateTime.Now
            }) > 0)
            {
                base.Response.Write("发表评论成功");
            }
            else
            {
                base.Response.Write("发表评论失败");
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 加入房间
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void JoinRoom(string ip, int port)
        {
            m_roomAddress = IPUtils.GetHostEndPoint(ip, port);
            
			PlayerData pd = new PlayerData ();
			pd.userId = m_mainUserId;
			pd.name = m_mainUserName;
            byte[] customPlayerData = PBSerializer.NSerialize(pd);

			RPC(m_roomAddress, FSPRoom.RPC_JoinRoom, m_mainUserId, m_mainUserName, customPlayerData);
        }
        public IActionResult Index()
        {
            /*
             * net core不自带httpcontext 需要在 Startup 注入
             * 1、在ConfigureServices 中 services.AddStaticHttpContext();
             * 2、在Configure 中 app.UseStaticHttpContext();
             */

            var builder = new StringBuilder("测试如下:\r\n");

            //Post
            builder.Append($"Post值:{WebUtils.GetFormVal<string>("a")}\r\n");

            //IP
            builder.Append($"IP:{IPUtils.GetIP()}\r\n");

            //WebUtils
            builder.Append($"pid:{WebUtils.GetQueryVal<int>("pid")}\r\n");                                  //?pid=1
            builder.Append($"date:{WebUtils.GetQueryVal<DateTime>("date", new DateTime(1900, 1, 1))}\r\n"); //?date=2020-12-31
            //全url
            builder.Append($"全URL:{WebUtils.GetAbsoluteUri()}\r\n");

            //CacheUtils 缓存
            DateTime dateTime = DateTime.Now;
            var      cache    = new CacheUtils();

            var cacheDT = DateTime.Now;

            if (cache.ContainKey("time"))
            {
                cacheDT = cache.Get <DateTime>("time");
            }
            else
            {
                cache.Insert <DateTime>("time", dateTime, 3600);
            }

            builder.Append($"当前时间:{dateTime.ToFormatString()} \r\n");
            builder.Append($"缓存时间:{cacheDT.ToFormatString()} \r\n");

            //当前网站目录
            builder.Append($"当前网站目录:{SystemUtils.GetMapPath()} \r\n");
            builder.Append($"upload目录:{SystemUtils.GetMapPath("/upload")} \r\n");

            //cookie
            CookieUtils.SetCookie("username", "jsonlee");
            builder.Append($"username cookie: {CookieUtils.GetCookie("username")} \r\n");

            //session
            SessionUtils.SetSession("username", System.Web.HttpUtility.UrlEncode("刘备"));
            builder.Append($"username session: {System.Web.HttpUtility.UrlDecode(SessionUtils.GetSession("username"))} \r\n");

            return(Content(builder.ToString()));
        }
Esempio n. 16
0
        public RtspServer(IAppConfigurationFacade appConfigurationFacade,
                          IRequestUrlVideoSourceResolverStrategy requestUrlVideoSourceResolverStrategy)
        {
            _portNumber = appConfigurationFacade.RtspServerPort;
            _requestUrlVideoSourceResolverStrategy = requestUrlVideoSourceResolverStrategy;
            if (_portNumber < System.Net.IPEndPoint.MinPort || _portNumber > System.Net.IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException("aPortNumber", _portNumber, "Port number must be between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort");
            }
            Contract.EndContractBlock();

            if (String.IsNullOrEmpty(appConfigurationFacade.RtspServerLogin) == false &&
                String.IsNullOrEmpty(appConfigurationFacade.RtspServerPassword) == false)
            {
                String realm = "SharpRTSPServer";
                var    authenticationParameters = new AuthenticationParameters()
                {
                    username           = appConfigurationFacade.RtspServerLogin,
                    password           = appConfigurationFacade.RtspServerPassword,
                    realm              = realm,
                    authenticationType = AuthenticationType.Digest,
                };
                _authentication = new Authentication(authenticationParameters, _logger);
            }
            else
            {
                _authentication = null;
            }

            RtspUtils.RegisterUri();

            Exception getIPException;

            _ipAddress = IPUtils.GetIPAddressFromString(appConfigurationFacade.RtspServerAddress, out getIPException);


            if (getIPException != null)
            {
                _logger.Error("Setting RtspServerAddress failed: " + getIPException);
            }

            _RTSPServerListener = new TcpListener(_ipAddress, _portNumber);

            try
            {
                StartListen();
            }
            catch (Exception ex)
            {
                _logger.Error($"Error: Could not start rtsp server on {_ipAddress}:{_portNumber} : " + ex.ToString());
                throw;
            }
        }
Esempio n. 17
0
        public void Test()
        {
            string str1 = "str1";
            string str2 = "str2";

            byte[] buff1 = UTF8Encoding.Default.GetBytes(str1);
            byte[] buff2 = UTF8Encoding.Default.GetBytes(str2);

            IPEndPoint target = IPUtils.GetHostEndPoint("127.0.0.1", 10002);

            RPC(target, "_RPC_Test", 1, 2, "abc", buff1, buff2);
        }
Esempio n. 18
0
        public IRtspClient Create(VideoSource videoSource)
        {
            Exception getIPexception;
            IPAddress ipAddress = IPUtils.GetIPAddressFromString(_appConfigurationFacade.RtspClientAddress, out getIPexception);

            if (getIPexception != null)
            {
                LogManager.GetLogger("RtspClientFactory").Error("Error getting RtspClient address: " + getIPexception);
            }

            return(new RTSPClient.RtspClient(videoSource, ipAddress));
        }
Esempio n. 19
0
        //================================逻辑=============================
        public void JoinRoom(string ip, int port)
        {
            m_roomAddress = IPUtils.GetHostEndPoint(ip, port);

            PlayerData player = new PlayerData();

            player.userID   = m_mainUserId;
            player.userName = m_mainUserName;
            byte[] customPlayerData = PBSerializer.Serialize(player);

            RPC(m_roomAddress, RoomRPC.RPC_JoinRoom, m_mainUserId, m_mainUserName, customPlayerData);
        }
Esempio n. 20
0
        public static bool HasCai(int intCommentID)
        {
            CommentActiveLogInfo model = BizBase.dbo.GetModel <CommentActiveLogInfo>(string.Concat(new object[]
            {
                " SELECT TOP 1 * FROM cms_CommentActiveLog WHERE IsCai=1 AND CommentID=",
                intCommentID,
                " AND IPAddress='",
                IPUtils.GetIP(),
                "' ORDER BY AutoID DESC "
            }));

            return(model != null);
        }
Esempio n. 21
0
    // Use this for initialization
    /// <summary>
    /// Start this instance.
    /// </summary>
    void Start()
    {
        SetDeviceInfo();
        SetPlayerInfo();
        Connect_SetValidationsOnInput();
        Player_SetValidationsOnInput();
        Player_PrepareUI();
        Preferences_PrepareUI();
        onChange = true;

        ui_connectionIpAdress.text = IPUtils.GetLocalAddress().ToString();
        ui_connectionPort.text     = 63001 + "";
    }
Esempio n. 22
0
        static public bool run()
        {
            Debug.Assert(IPUtils.ParseIPAddress("dfdf") == null);
            Debug.Assert(IPUtils.ParseIPAddress("256.2.3.4") == null);
            Debug.Assert(IPUtils.ParseIPAddress("2.3.4") == null);

            UInt16[] ip = IPUtils.ParseIPAddress("1.2.3.4");
            Debug.Assert(ip[0] == 1);
            Debug.Assert(ip[1] == 2);
            Debug.Assert(ip[2] == 3);
            Debug.Assert(ip[3] == 4);
            return(true);
        }
Esempio n. 23
0
 private void LogUserLogged(User user)
 {
     Common.CSVLogger.CSVLogger.Instance.Log(new Common.CSVLogger.CSVLog
     {
         Action      = ActionContext.ActionDescriptor.ActionName,
         Controller  = ActionContext.ControllerContext.ControllerDescriptor.ControllerName,
         Date        = DateTime.UtcNow,
         Description = "User Logged in",
         IP          = IPUtils.GetClientIp(Request),
         UserEmail   = user.Email,
         Username    = user.UserName
     });
 }
        public ActionResult Index()
        {
            var builder = new StringBuilder("测试如下:<br/>\r\n");

            //IP
            builder.Append($"IP:{IPUtils.GetIP()}<br/>\r\n");

            //WebUtils
            builder.Append($"pid:{WebUtils.GetQueryInt("pid")}<br/>\r\n"); //?pid=1
            //全url
            builder.Append($"全URL:{WebUtils.GetAbsoluteUri()}<br/>\r\n");

            //CacheUtils 缓存
            DateTime dateTime = DateTime.Now;
            var      cache    = new CacheUtils();

            var cacheDT = DateTime.Now;

            if (cache.ContainKey("time"))
            {
                cacheDT = cache.Get <DateTime>("time");
            }
            else
            {
                cache.Insert <DateTime>("time", dateTime, 3600);
            }

            builder.Append($"当前时间:{dateTime.ToFormatString()} <br/>\r\n");
            builder.Append($"缓存时间:{cacheDT.ToFormatString()} <br/>\r\n");

            //当前网站目录
            builder.Append($"当前网站目录:{SystemUtils.GetMapPath()} <br/>");
            builder.Append($"upload目录:{SystemUtils.GetMapPath("/upload")} <br/>");

            //cookie
            CookieUtils.SetCookie("username", "jsonlee");
            builder.Append($"username cookie: {CookieUtils.GetCookie("username")} <br/>\r\n");

            //session
            SessionUtils.SetSession("username", "刘备");
            builder.Append($"username session: {SessionUtils.GetSession<string>("username")}  <br/>\r\n");

            builder.Append($"mobile client : {SystemUtils.IsMobileClient.Value} <br/>\r\n");
            builder.Append($"weixin client : {SystemUtils.IsWeixinClient.Value} <br/>\r\n");

            builder.Append($"is iphone : {SystemUtils.IsIphone.Value} <br/>\r\n");
            builder.Append($"is android : {SystemUtils.IsAndroid.Value} <br/>\r\n");

            return(Content(builder.ToString()));
        }
        internal UIDGeneratorIPImpl(IPUIDOptions options)
        {
            EpochDateTime = options.EpochDateTime;

            MaxTimestamp   = BitUtils.MaxVaue(TimestampBit);
            MaxSequence    = BitUtils.MaxVaue(SequenceBit);
            MaxTimeCheck   = BitUtils.MaxVaue(TimeCheckBit);
            MaxIp          = BitUtils.MaxVaue(IpBit);
            IP             = IPUtils.IPToInt() & 0x0000ffff; //取后2位
            IpShift        = 0;
            TimeCheckShift = IpBit;
            SequenceShift  = TimeCheckBit + IpBit;
            TimestampShift = SequenceBit + TimeCheckBit + IpBit;
        }
Esempio n. 26
0
        public void TestIPArea()
        {
            /*
             * 1、在nuget包管理里面加入 System.Text.Encoding.CodePages
             * 2、注册 System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
             * 这样就支持 gb2312 了
             */
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            //var ip = "218.95.66.68";
            //Console.WriteLine("IP定位:"+new IPScanner().IPLocation(ip));

            Console.WriteLine("IP定位:" + IPUtils.GetIPAreaStr());
        }
Esempio n. 27
0
 /// <summary>
 /// 注册服务
 /// </summary>
 /// <param name="GrpcServerRegister">服务注册</param>
 /// <returns></returns>
 public override Entry RegisterService(GrpcServerRegister grpcServerRegister)
 {
     try
     {
         if (string.IsNullOrEmpty(grpcServerRegister.Host))
         {
             grpcServerRegister.Host = IPUtils.GetAddressIP();
         }
         var serviceId = $"{grpcServerRegister.ServiceName}_{grpcServerRegister.Host}:{grpcServerRegister.Port}";
         var acr       = new AgentCheckRegistration
         {
             TCP      = $"{grpcServerRegister.Host}:{grpcServerRegister.Port}",
             Name     = serviceId,
             ID       = serviceId,
             Interval = GlobalConfig.CheckInterval,
             DeregisterCriticalServiceAfter = GlobalConfig.CriticalInterval
         };
         if (grpcServerRegister.Meta == null)
         {
             grpcServerRegister.Meta = new Dictionary <string, string>();
         }
         if (!grpcServerRegister.Meta.ContainsKey("weights"))
         {
             grpcServerRegister.Meta.Add("weights", "1");
         } //权重值,如果等于0,客户端会自动移除
         var asr = new AgentServiceRegistration
         {
             Address           = grpcServerRegister.Host,
             ID                = serviceId,
             Name              = grpcServerRegister.ServiceName,
             Port              = grpcServerRegister.Port,
             Check             = acr,
             Tags              = grpcServerRegister.Tags,
             Meta              = grpcServerRegister.Meta,
             EnableTagOverride = grpcServerRegister.EnableTagOverride
         };
         var res = _clientManager.GetClient.Agent.ServiceRegister(asr).Result;
         if (res.StatusCode != HttpStatusCode.OK)
         {
             throw new GrpcConsulException($"Failed to register service by {serviceId}");
         }
         return(new Entry(this, serviceId, grpcServerRegister.ServiceName, grpcServerRegister.Host, grpcServerRegister.Port));
     }
     catch (Exception ex)
     {
         CommonUtilsHelper._.LoggerWriter(ex.Message, ex);
     }
     return(null);
 }
Esempio n. 28
0
        public void Start()
        {
            Debuger.Log();

            m_IsRunning = true;

            m_SystemSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            m_SystemSocket.Bind(IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, m_port));

            m_ThreadRecv = new Thread(Thread_Recv)
            {
                IsBackground = true
            };
            m_ThreadRecv.Start();
        }
Esempio n. 29
0
        //------------------------------------------------------------
        #region 绑定端口函数
        public int Bind(int port = 0)
        {
            Debuger.Log(LOG_TAG, "Bind() port = " + port);
            if (m_SystemSocket == null)
            {
                return(0);
            }

            //如果Bind的端口为0,则会随机分配一个端口
            IPEndPoint ipep = IPUtils.GetIPEndPointAny(m_AddrFamily, port);

            m_SystemSocket.Bind(ipep);
            m_IsActive = true;
            return(SelfPort);
        }
Esempio n. 30
0
        private void DoReceiveInThread()
        {
            EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0);
            int      cnt         = m_SystemSocket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint);

            if (cnt > 0)
            {
                byte[] dst = new byte[cnt];
                Buffer.BlockCopy(m_RecvBufferTemp, 0, dst, 0, cnt);

                lock (m_RecvBufferQueue)
                {
                    m_RecvBufferQueue.Enqueue(dst);
                }
            }
        }