コード例 #1
0
 /// <summary>
 /// 启动
 /// </summary>
 /// <param name="backlog"> 挂起的连接队列的最大长度。</param>
 public void Start(int backlog = 10)
 {
     SOCKET_SERVER.Bind(IPE);
     SOCKET_SERVER.Listen(backlog);
     SOCKET_SERVER.BeginAccept(new AsyncCallback(BeginAcceptConnection), null);
     Log4netHelper.Debug($"监听{IPE.Address.ToString()}成功");
 }
コード例 #2
0
 /// <summary>
 /// 关闭连接
 /// </summary>
 /// <param name="ex">异常信息,如果主动关闭未Null,如果异常引发关闭则是异常信息</param>
 public void Close(Exception ex = null)
 {
     if (!this.IsDisposable)
     {
         lock (Socket)
         {
             if (!this.IsDisposable)
             {
                 Log4netHelper.Debug($"正在关闭客户端与服务端的链接:{IPE.Address.ToString()}");
                 Socket.Shutdown(SocketShutdown.Both);
                 Socket.Close();
                 Socket.Dispose();
                 IsDisposable = true;
                 if (CloseCallback != null)
                 {
                     try
                     {
                         CloseCallback(ex);
                     }
                     catch (Exception close_ex)
                     {
                         Log4netHelper.Fatal($"客户端接收到消息但执行DisposeCallback异常", close_ex);
                     }
                 }
             }
         }
     }
 }
コード例 #3
0
        /// <summary>
        ///接收消息
        /// </summary>
        /// <returns></returns>
        private byte[] Receive(byte[] buffer)
        {
            int receiveBytes = 0;

            try
            {
                var receive_buffer = new byte[Receive_Buffer_Size];
                receiveBytes = this.Socket.Receive(receive_buffer); //receiveBytes长度小于等于buffer的长度
                byte[] add_buffer      = null;                      //新接收到的数据
                byte[] transfer_buffer = null;                      //中转变量,存储已经接收到的数据
                while (this.Socket.Available > 0)
                {
                    add_buffer = new byte[Receive_Buffer_Size];
                    var add_receiveBytes = this.Socket.Receive(add_buffer);

                    receiveBytes += add_receiveBytes;
                    //创建新增存储对象
                    transfer_buffer = new byte[receiveBytes];
                    //将历史数据复制到新的存储对象
                    Array.Copy(receive_buffer, 0, transfer_buffer, 0, receiveBytes - add_receiveBytes);
                    //将新增的数据复制打中转存储对象
                    Array.Copy(add_buffer, 0, transfer_buffer, receiveBytes - add_receiveBytes, add_receiveBytes);
                    receive_buffer = transfer_buffer;
                }
                if (receiveBytes <= 0)
                {
                    Log4netHelper.Debug($"接受到服务端{this.ToJson()}{receiveBytes}个字节,自动关闭连接");
                    this.Close(new Exception($"接受到服务端{receiveBytes}个字节,自动关闭连接"));
                }
                if (buffer != null)
                {
                    transfer_buffer = new byte[buffer.Length + receive_buffer.Length];
                    Array.Copy(buffer, 0, transfer_buffer, 0, buffer.Length);
                    Array.Copy(receive_buffer, 0, transfer_buffer, buffer.Length, receive_buffer.Length);
                    return(transfer_buffer);
                }
                else
                {
                    if (receiveBytes < receive_buffer.Length)
                    {
                        return(receive_buffer.Take(receiveBytes).ToArray());
                    }
                    return(receive_buffer);
                }
            }
            catch (Exception ex)
            {
                Log4netHelper.Fatal($"客户端{this.ToJson()}接受消息时异常,自动关闭连接", ex);
                this.Close(ex);
                if (this.ReciveExceptionCallback != null)
                {
                    this.ReciveExceptionCallback(ex);
                }
            }
            return(null);
        }
コード例 #4
0
 /// <summary>
 /// 停止
 /// </summary>
 public void Stop()
 {
     if (!this.IsDisposable)
     {
         SendAll("服务端请求断开链接");
         Log4netHelper.Debug("正在关闭服务端");
         SOCKET_SERVER.Close();
         SOCKET_SERVER.Dispose();
         this.IsDisposable = true;
     }
 }
コード例 #5
0
        public DataTable GetReportDataSource(string strWhere, string userCode, int pageIndex, int pageSize)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("SELECT TOP (" + pageSize + ") * FROM \n");
            builder.Append("( \n");
            builder.Append("SELECT Row_Number() OVER (ORDER BY Date DESC, Version ASC) as Num,* FROM ( \n");
            builder.Append("SELECT c.ContractID,ContractCode,ContractName,BName,ModifiedMoney,c.conState,Convert(NVARCHAR(10),SignDate,121) AS SignDate,TypeName,ISNULL(PT_PrjInfo.PrjName,PT_PrjInfo_ZTB.PrjName) as PrjName, ").AppendLine();
            builder.Append("ISNULL(SUM(PaymentMoney),0) AS PaymentTotal, ISNULL(SUM(PaymentMoney)/NULLIF(ModifiedMoney,0),0) AS Rate, YH.v_xm AS SignPersonName, ").AppendLine();
            builder.Append("CASE IsMainContract ").AppendLine();
            builder.Append("\t   WHEN 1 THEN c.ContractID ").AppendLine();
            builder.Append("\t   WHEN 0 THEN MainContractID + c.ContractID ").AppendLine();
            builder.Append("END AS Version,").AppendLine();
            builder.Append("CASE IsMainContract ").AppendLine();
            builder.Append("     WHEN 1 THEN c.InputDate").AppendLine();
            builder.Append("     WHEN 0 THEN (SELECT c2.InputDate FROM Con_Payout_Contract c1").AppendLine();
            builder.Append("                  JOIN Con_Payout_Contract c2 ON c1.MainContractID = c1.ContractID").AppendLine();
            builder.Append("                  WHERE c1.ContractID = c.ContractID").AppendLine();
            builder.Append("                 )").AppendLine();
            builder.Append("END AS Date,").AppendLine();
            builder.Append("IsMainContract,c.UserCodes,ISNULL(CorpName,BName) AS CorpName,PrjType.CodeName  ").AppendLine();
            builder.Append("FROM Con_Payout_Contract c").AppendLine();
            builder.Append("LEFT JOIN Con_Payout_Payment ON Con_Payout_Payment.ContractID = c.ContractID ").AppendLine();
            builder.Append("AND Con_Payout_Payment.FlowState = '1' ").AppendLine();
            builder.Append("LEFT JOIN Con_ContractType ON Con_ContractType.TypeID = c.TypeID  ").AppendLine();
            builder.Append("LEFT JOIN PT_PrjInfo ON PT_PrjInfo.PrjGuid = c.PrjGuid ").AppendLine();
            builder.Append("LEFT JOIN PT_yhmc YH ON YH.v_yhdm = c.SignPerson").AppendLine();
            builder.Append("LEFT JOIN PT_PrjInfo_ZTB on c.PrjGuid = PT_PrjInfo_ZTB.PrjGuid").AppendLine();
            builder.Append("LEFT JOIN XPM_Basic_ContactCorp ON BName=CAST(CorpId AS NVARCHAR(1024))  ").AppendLine();
            builder.Append(" LEFT JOIN( SELECT prjGuid,STUFF((select ','+[CodeName] FROM PT_PrjInfo_Kind ").AppendLine();
            builder.Append(" LEFT JOIN XPM_Basic_CodeList on XPM_Basic_CodeList.CodeID=PT_PrjInfo_Kind.PrjKind ").AppendLine();
            builder.Append(" WHERE PrjGuid=PrjInfo_PrjKind.PrjGuid AND isvalid=1 AND TypeID=(SELECT TypeID FROM XPM_Basic_CodeType WHERE SignCode='ProjectType') FOR XML PATH('')),1,1,'') CodeName ").AppendLine();
            builder.Append(" FROM PT_PrjInfo_Kind as PrjInfo_PrjKind GROUP by[PrjGuid] ) PrjType ON c.PrjGuid = PrjType.PrjGuid ").AppendLine();
            builder.Append("WHERE c.FlowState = '1' ").AppendLine();
            builder.Append("AND c.PrjGuid != '' ").AppendLine();
            builder.Append("AND c.UserCodes  LIKE '%" + userCode + "%'").AppendLine();
            if (!string.IsNullOrEmpty(strWhere))
            {
                if (strWhere.Contains("Con_Payout_Contract"))
                {
                    strWhere = strWhere.Replace("Con_Payout_Contract", "c");
                }
                builder.Append(" AND ").Append(strWhere).AppendLine();
            }
            builder.Append(" GROUP BY c.ContractID,ContractCode,ContractName,BName,ModifiedMoney,c.conState,SignDate,TypeName,PT_PrjInfo.PrjName,PT_PrjInfo_ZTB.PrjName, ").AppendLine();
            builder.Append("IsMainContract,MainContractID,c.InputDate,c.UserCodes,CorpName,PrjType.CodeName, YH.v_xm ").AppendLine();
            builder.Append(") Y \n");
            builder.Append(") T \n");
            builder.Append(string.Concat(new object[] { "WHERE Num > (", pageIndex, "-1)*", pageSize, " \n" }));
            Log4netHelper.Debug(builder.ToString(), "");
            return(SqlHelper.ExecuteQuery(CommandType.Text, builder.ToString(), null));
        }
コード例 #6
0
        /// <summary>
        /// 发送POTS 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="headers"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        private static string HttpPost(string url, string data, Dictionary <string, string> headers = null, string charset = "UTF-8", int timeout = 15000)
        {
#if DEBUG
            timeout = 1000 * 60 * 10;
#endif
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method            = "POST";
            request.ContentType       = "application/x-www-form-urlencoded";
            request.Accept            = "*/*";
            request.Timeout           = timeout;
            request.AllowAutoRedirect = false;
            SetHeaders(request, headers);
            byte[] paramBytes = Encoding.GetEncoding(charset).GetBytes(data);
            request.ContentLength = paramBytes.Length;
            string responseStr = string.Empty;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(paramBytes, 0, paramBytes.Length);
                requestStream.Close();
                try
                {
                    var response = request.GetResponse();
                    if (response != null)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        {
                            responseStr = reader.ReadToEnd();
                        }
                    }
                }
                catch (WebException ex)
                {
                    Log4netHelper.Fatal("HttpPost异常", ex);
                    var response = (HttpWebResponse)ex.Response;
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            responseStr = reader.ReadToEnd();
                        }
                    }
                    Log4netHelper.Debug(url, responseStr);
                    throw ex;
                }
                return(responseStr);
            }
        }
コード例 #7
0
 /// <summary>
 /// 开始接受消息
 /// </summary>
 /// <param name="ar"></param>
 private void Receive()
 {
     while (this.Socket.Connected)
     {
         byte[] buffer       = new byte[1024 * 1024 * 2];
         var    receiveBytes = this.Socket.Receive(buffer);
         if (receiveBytes <= 0)
         {
             Log4netHelper.Debug($"服务端接受到{receiveBytes}个字节,客户端已断开连接");
             this.Close();
         }
         else
         {
             var msg = Encoding.UTF8.GetString(buffer, 0, receiveBytes);
             Log4netHelper.Debug($"服务端接受到来自{this.RemoteEndPoint}的{receiveBytes}个字节消息:{msg}");
             ReceiveCallbackAsync(this, msg);
         }
     }
 }
コード例 #8
0
 /// <summary>
 /// 发送消息
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="content"></param>
 public void Send <T>(T obj)
 {
     try
     {
         var    msg       = JsonHelper.SerializeObject(obj);
         byte[] buffer    = Encoding.UTF8.GetBytes($"{msg.EncryptBase64(encode: Encoding.UTF8)}{SocketCommand.MessageSeparator}");
         var    send_byte = Socket.Send(buffer, buffer.Length, SocketFlags.None);
         if (send_byte < buffer.Length)
         {
             throw new Exception($"send_byte={send_byte}<buffer.length={buffer.Length}");
         }
         Log4netHelper.Info($"发送{buffer.Length}字节,实际发送{send_byte}字节{Environment.NewLine}{msg}");
     }
     catch (Exception ex)
     {
         if (this.SendExceptionCallback != null)
         {
             this.SendExceptionCallback(ex, obj);
         }
         Log4netHelper.Debug($"发送消息异常:{obj.ToJson()}", ex);
         throw ex;
     }
 }
コード例 #9
0
 /// <summary>
 /// 启动
 /// </summary>
 public void Start()
 {
     try
     {
         Socket.Connect(IPE);
         if (!Socket.Connected)
         {
             throw new Exception($"{this.LocalAddress}与{IPE.Address.ToString()}建立连接失败,状态为={this.Socket.Connected}");
         }
     }
     catch (Exception ex)
     {
         if (this.ConnectCallback != null)
         {
             this.ConnectCallback(ex);
         }
         throw ex;
     }
     this.LocalAddress = ((System.Net.IPEndPoint) this.Socket.LocalEndPoint).ToString();
     Log4netHelper.Debug($"{this.LocalAddress}已建立与{IPE.Address.ToString()}的连接");
     if (this.ConnectCallback != null)
     {
         this.ConnectCallback(null);
     }
     TrySetKeepAlive(5, 5);
     Task.Run(() =>
     {
         try
         {
             Receive();
         }
         catch (Exception ex)
         {
             Log4netHelper.Fatal("Recive异常", ex);
         }
     });
 }
コード例 #10
0
        /// <summary>
        /// 接收消息
        /// </summary>
        public void Receive()
        {
            if (!isRunning || socket == null)
            {
                Thread.Sleep(100);
                return;
            }

            if (socket.Poll(200000, SelectMode.SelectRead))
            {
                //512k
                byte[] buffer = new byte[1024 * 512];
                int    count  = socket.Receive(buffer, buffer.Length, SocketFlags.None);
                if (count == 0)
                {
                    isRunning = false;
                }
                else
                {
                    Encoding encoding = Encoding.GetEncoding("UTF-8");
                    Log4netHelper.Debug(string.Format("接收到数据:{0}", encoding.GetString(buffer, 0, count)));
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// 接受连接
        /// </summary>
        /// <param name="ar"></param>
        private void BeginAcceptConnection(IAsyncResult ar)
        {
            if (this.IsDisposable)
            {
                return;
            }
            var socket         = SOCKET_SERVER.EndAccept(ar);
            var remoteEndPoint = ((System.Net.IPEndPoint)socket.RemoteEndPoint);

            Log4netHelper.Debug($"{remoteEndPoint.Address.ToString()}连接到了本服务端");
            var session = new SocketSession(socket)
            {
                Id              = Guid.NewGuid().ToString(),
                RemoteEndPoint  = socket.RemoteEndPoint,
                ReceiveCallback = (obj, msg) =>
                {
                    try
                    {
                        ReceiveEvent(obj, msg);
                    }
                    catch (Exception ex)
                    {
                        Log4netHelper.Fatal($"服务端在执行ReceiveEvent事件时发生异常{Environment.NewLine}消息内容{msg}{Environment.NewLine}会话{JsonHelper.SerializeObject(obj)}", ex);
                    }
                },
                DisposeCallback = (obj) =>
                {
                    SESSIONS.Remove(obj);
                },
            };

            session.Start();
            SESSIONS.Add(session);
            SOCKET_SERVER.BeginAccept(new AsyncCallback(BeginAcceptConnection), null);
            AcceptConnectionEvent(session, null);
        }
コード例 #12
0
        /// <summary>
        /// 为本客户端创建一个新的会话
        /// </summary>
        /// <returns></returns>
        public SocketClient CreateSession()
        {
            var socketClient = new SocketClient(IPAddress.Parse(this.Ip), this.Port);

            socketClient.ReceiveCallback = (msg) =>
            {
                if (this.ReceiveCallback != null)
                {
                    this.ReceiveCallback(this, socketClient, msg);
                }
            };
            socketClient.CloseCallback = (ex) =>
            {
                if (this.CloseCallback != null)
                {
                    this.CloseCallback(this, socketClient, ex);
                }
                SocketClient output;
                if (!this.Sessions.TryRemove(socketClient.LocalAddress, out output))
                {
                    Log4netHelper.Debug($"会话关闭后,移除会话失败{socketClient.LocalAddress}");
                }
                if (ex != null)
                {
                    //如果是异常引发的关闭,则重新尝试连接
                    Policy.Handle <Exception>().WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(Math.Pow(1, retryAttempt)), (policy_ex, timer) =>
                    {
                        var msg = $"{socketClient.LocalAddress}异常关闭,正在重新连接,timer={timer.TotalSeconds} ex={policy_ex.Message}";
                        socketClient.ConnectCallback(new Exception(msg));
                    }).Execute(() =>
                    {
                        CreateSession();
                    });
                }
            };
            socketClient.SendExceptionCallback = (ex, message) =>
            {
                if (this.SendExceptionCallback != null)
                {
                    this.SendExceptionCallback(this, socketClient, ex, message.ToString());
                }
            };
            socketClient.ReciveExceptionCallback = (ex) =>
            {
                if (this.ReciveExceptionCallback != null)
                {
                    this.ReciveExceptionCallback(this, socketClient, ex);
                }
            };
            socketClient.ConnectCallback = (ex) =>
            {
                if (this.ConnectCallback != null)
                {
                    this.ConnectCallback(this, socketClient, ex);
                }
            };
            socketClient.Start();
            if (!this.Sessions.TryAdd(socketClient.LocalAddress, socketClient))
            {
                Log4netHelper.Debug($"{socketClient.LocalAddress}与服务端建立连接后插入会话集合失败");
            }
            this.Status = ClientModelStatusEnum.Running;
            return(socketClient);
        }