コード例 #1
0
        private void transfer(Object obj)
        {
            ConnectionHub connectionHub = obj as ConnectionHub;
            TcpClient     tc1           = connectionHub.Source;
            var           ns01          = tc1.GetStream();

            try
            {
                string clientmessage = "";
                byte[] bytes         = ReadMessage(ref ns01);
                if (bytes == null || bytes.Length == 0)
                {
                    return;
                }
                ConnTargetServer(ns01, "", bytes);
            }
            catch (Exception e01)
            {
            }
            finally
            {
                tc1.Close();
                ns01.Close();
                //tc2.Close();
            }
        }
コード例 #2
0
        private void AcceptClient()
        {
            int i = 0;

            while (true)
            {
                try
                {
                    i++;
                    TcpClient tc1 = tcpListener.AcceptTcpClient(); //这里是等待数据再执行下边,不会100%占用cpu
                    tc1.SendTimeout    = 300000;                   //设定超时,否则端口将一直被占用,即使失去连接
                    tc1.ReceiveTimeout = 300000;
                    var           guid = Guid.NewGuid().ToString("N");
                    ConnectionHub obj1 = new ConnectionHub {
                        ID = guid, Source = tc1
                    };
                    //限流要做两件事
                    //限制当前同时连接数
                    //限制一个同一IP请求频率
                    //总体限流
                    string remotepoint = (tc1.Client.RemoteEndPoint as IPEndPoint).Address.ToString();
                    //Console.WriteLine("Client " + remotepoint);
                    var r01 = limitingService.Request(remotepoint);
                    if (i >= 1000)
                    {
                        LogManager.Instance.Log(ELogtype.Info, GetNodeNum(remotepoint));
                        LogManager.Instance.Log(ELogtype.Info, "剩余可用令牌:" + limitingService.GetAvailableTokenNum());
                        i = 0;
                    }
                    if (r01)
                    {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(transfer), obj1);
                    }
                    else
                    {
                        var E509 = remotepoint + " 限制访问,剩余可用令牌:" + limitingService.GetAvailableTokenNum();
                        SendMessage(tc1.GetStream(), Encoding.UTF8.GetBytes(E509));
                        LogManager.Instance.Log(ELogtype.Info, E509);
                        tc1.Close();
                    }
                    //Console.WriteLine("Client " + remotepoint + " Disconnect..");
                }
                catch (Exception e01)
                {
                    LogManager.Instance.Log(ELogtype.Error, "", e01);
                }
            }
        }