Exemplo n.º 1
0
        private void Listening()
        {
            while (!stop)
            {
                try
                {
                    Socket socket = socketServer.Accept();

                    socket.NoDelay = true;
                    IPEndPoint endPoint  = (IPEndPoint)socket.RemoteEndPoint;
                    Session    appSocket = new Session();
                    appSocket.IPAddress = endPoint.Address.ToString();
                    appSocket.Port      = endPoint.Port;
                    appSocket.IsValid   = true;
                    appSocket.SessionID = SocketApplicationComm.GetSeqNum();
                    appSocket.Socket    = socket;


                    //_connectSocketBagList.Add(appSocket);
                    _connectSocketDic.TryAdd(appSocket.SessionID, appSocket);
                }
                catch (Exception e)
                {
                    OnError(e);
                }
            }

            socketServer.Close();
            SocketApplicationComm.Debug("关闭服务器套接字!");
        }
Exemplo n.º 2
0
        /// <summary>
        /// 发送soa通知
        /// </summary>
        /// <param name="recivers"></param>
        /// <param name="type"></param>
        /// <param name="body"></param>
        /// <param name="needresult"></param>
        /// <returns></returns>
        public SOANoticeResponse SendNotice(string[] recivers, int type, byte[] body, bool needresult)
        {
            if (recivers == null || recivers.Length == 0)
            {
                return(new SOANoticeResponse());
            }

            Message m = new Message((int)SOAMessageType.SOANoticeRequest);

            m.SetMessageBody(new Contract.SOANoticeRequest
            {
                NeedResult    = needresult,
                NoticeBody    = body,
                NoticeType    = type,
                ReciveClients = recivers
            });

            if (needresult)
            {
                m.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
                return(SendMessageAnsy <Contract.SOANoticeResponse>(m));
            }
            else
            {
                return(new SOANoticeResponse
                {
                    IsDone = SendMessage(m)
                });
            }
        }
Exemplo n.º 3
0
        public bool RegisterService()
        {
            if (this.ServiceNo < 0)
            {
                throw new Exception("注册服务失败:服务号不能为负数");
            }

            StartRedirectService();

            Message msg = new Message((int)SOAMessageType.RegisterService);

            msg.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
            RegisterServiceRequest req = new RegisterServiceRequest();

            req.ServiceNo = this.ServiceNo;
            if (SupportTcpServiceRidrect)
            {
                req.RedirectTcpIps  = RedirectTcpServiceServer.GetBindIps();
                req.RedirectTcpPort = RedirectTcpServiceServer.GetBindTcpPort();
            }
            if (SupportUDPServiceRedirect)
            {
                req.RedirectUdpIps  = RedirectUpdServiceServer.GetBindIps();
                req.RedirectUdpPort = RedirectUpdServiceServer.GetBindUdpPort();
            }

            msg.SetMessageBody(req);

            bool boo = SendMessageAnsy <RegisterServiceResponse>(msg).IsSuccess;

            return(boo);
        }
Exemplo n.º 4
0
        public bool SendFile(string localfile, string rename, int sendsplitcount, Action <double> process, bool resend = false)
        {
            int    count     = sendsplitcount <= 0 ? 1024 * 100 : sendsplitcount;
            string filename  = string.IsNullOrWhiteSpace(rename) ? System.IO.Path.GetFileName(localfile) : rename;
            var    sendbytes = 0L;

            if (resend)
            {
                Message msg = new Message(MessageType.SENDFILRESENDCHECK);
                msg.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
                msg.SetMessageBody(new SendFileCheckRequestMessage {
                    FileName = filename
                });
                sendbytes = SendMessageAnsy <SendFileCheckResponseMessage>(msg).FileLength;
            }

            byte[] buffer = new byte[count];
            using (System.IO.FileStream fs = new System.IO.FileStream(localfile, System.IO.FileMode.Open))
            {
                var total = fs.Length;
                if (sendbytes > 0)
                {
                    fs.Position = sendbytes;
                }
                while (true)
                {
                    var len = fs.Read(buffer, 0, count);
                    if (len > 0)
                    {
                        SendFileMessage filemsg = new SendFileMessage()
                        {
                            FileBytes = len < count?buffer.Take(len).ToArray() : buffer, FileName = filename
                        };
                        Message msg = new Message(MessageType.SENDFILE);
                        msg.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
                        msg.SetMessageBody(filemsg);
                        if (!SendMessageAnsy <SendFileECHOMessage>(msg).IsSuccess)
                        {
                            return(false);
                        }
                        sendbytes += len;
                        if (process != null)
                        {
                            process(Math.Round((sendbytes * 1.0 / total), 4));
                        }
                    }
                    else
                    {
                        if (process != null)
                        {
                            process(1);
                        }
                        break;
                    }
                }
            }

            return(true);
        }
Exemplo n.º 5
0
        private void App_HeatBeat(Message message, UDPSession session)
        {
            Message msg = new Message(MessageType.HEARTBEAT);

            msg.SetMessageBody(session.SessionID);

            session.LastSessionTime = DateTime.Now;
            session.SendMessage(msg);

            SocketApplicationComm.Debug(string.Format("{0}发来心跳!", session.SessionID));
        }
Exemplo n.º 6
0
        private void OnSocket(object obj)
        {
            Socket socket = (Socket)obj;

            socket.NoDelay = true;
            IPEndPoint endPoint = (IPEndPoint)socket.RemoteEndPoint;

            Session appSocket = new Session();

            appSocket.IPAddress = endPoint.Address.ToString();
            appSocket.IsValid   = true;
            appSocket.SessionID = SocketApplicationComm.GetSeqNum();
            appSocket.Socket    = socket;

            while (appSocket.IsValid && appSocket.Socket.Connected)
            {
                try
                {
                    var buffer = ReceivingNext(socket);

                    //搞成异步的
                    new Action <byte[], Session>((b, s) =>
                    {
                        Message message   = EntityBufCore.DeSerialize <Message>(b);
                        s.LastSessionTime = DateTime.Now;
                        FormApp(message, s);
                    }).BeginInvoke(buffer, appSocket, null, null);
                }
                catch (SessionAbortException exp)
                {
                    SocketApplicationComm.Debug(exp.Message);
                    break;
                }
                catch (SocketException exp)
                {
                    SocketApplicationComm.Debug(exp.Message);
                    break;
                }
                catch (Exception exp)
                {
                    SocketApplicationComm.Debug(exp.Message);
                    OnError(exp);
                }
            }
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            SocketApplicationComm.Debug(string.Format("服务器关闭套接字:{0}", appSocket.SessionID));
        }
        internal T DoRequest <T>(int funcid, object param)
        {
            SOARedirectRequest request = new SOARedirectRequest();

            request.FuncId = funcid;
            if (param == null)
            {
                request.Param = null;
            }
            else
            {
                request.Param = EntityBufCore.Serialize(param);
            }

            Message msg = new Message((int)SOAMessageType.DoSOARedirectRequest);

            msg.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
            msg.MessageBuffer = EntityBufCore.Serialize(request);

            try
            {
                var resp = SendMessageAnsy <SOARedirectResponse>(msg, timeOut: 5000);
                if (TimeOutTimes > 0)
                {
                    TimeOutTimes--;
                }
                if (resp.IsSuccess)
                {
                    return(EntityBuf.EntityBufCore.DeSerialize <T>(resp.Result));
                }
                else
                {
                    throw new Exception(resp.ErrMsg);
                }
            }
            catch (TimeoutException ex)
            {
                TimeOutTimes++;

                if (TimeOutTimes > MAXTIMEOUTTIMES)
                {
                    OnError(new System.Net.WebException("一段时间内连续超时,可能出现网络问题"));
                }

                throw ex;
            }
        }
Exemplo n.º 8
0
        public void UnRegisterService()
        {
            Message msg = new Message((int)SOAMessageType.UnRegisterService);

            msg.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
            UnRegisterServiceRequest req = new UnRegisterServiceRequest();

            req.ServiceNo = this.ServiceNo;
            msg.SetMessageBody(req);

            bool boo = SendMessageAnsy <UnRegisterServiceResponse>(msg).IsSuccess;

            if (boo)
            {
                Console.WriteLine("取消注册成功");
            }
        }
Exemplo n.º 9
0
        private void StartHearteBeat(LoginResponseMessage message)
        {
            SessionContext                  = new Session();
            SessionContext.UserName         = message.LoginID;
            SessionContext.ConnectTime      = DateTime.Now;
            SessionContext.SessionID        = SocketApplicationComm.GetSeqNum();
            SessionContext.SessionTimeOut   = message.SessionTimeOut;
            SessionContext.HeadBeatInterVal = message.HeadBeatInterVal;
            SessionContext.IsLogin          = true;
            SessionContext.IsValid          = true;

            if (timer == null)
            {
                timer          = new Timer(SessionContext.HeadBeatInterVal);
                timer.Elapsed += HeartBeat_Elapsed;
                timer.Start();
            }
        }
Exemplo n.º 10
0
        void Args_Completed(object sender, SocketAsyncEventArgs e)
        {
            Listening();

            e.Completed -= Args_Completed;

            Socket socket = e.AcceptSocket;

            socket.NoDelay = true;

            IPEndPoint endPoint  = (IPEndPoint)socket.RemoteEndPoint;
            Session    appSocket = new Session();

            appSocket.IPAddress   = endPoint.Address.ToString();
            appSocket.IsValid     = true;
            appSocket.SessionID   = SocketApplicationComm.GetSeqNum();
            appSocket.Socket      = socket;
            appSocket.Port        = endPoint.Port;
            appSocket.ConnectTime = DateTime.Now;

            var socketAsyncEventArgs = e as IOCPSocketAsyncEventArgs;

            socketAsyncEventArgs.AcceptSocket = socket;
            socketAsyncEventArgs.Completed   += SocketAsyncEventArgs_Completed;
            socketAsyncEventArgs.UserToken    = appSocket.SessionID;

            //byte[] buffer = new byte[4];
            //socketAsyncEventArgs.SetBuffer(buffer, 0, 4);
            SetBuffer(socketAsyncEventArgs, 0, 4);
            //socketAsyncEventArgs.SetBuffer(_bufferpoll.Buffer, _bufferpoll.GetOffset(socketAsyncEventArgs.BufferIndex), 4);

            _connectSocketDic.TryAdd(appSocket.SessionID, appSocket);

            if (!socket.ReceiveAsync(socketAsyncEventArgs))
            {
                //Session old;
                //_connectSocketDic.TryRemove(appSocket.SessionID, out old);
                //RealseSocketAsyncEventArgs(socketAsyncEventArgs);

                LogManager.LogHelper.Instance.Debug(socket.Handle + "同步完成,手动处理");

                SocketAsyncEventArgs_Completed(null, e);
            }
        }
Exemplo n.º 11
0
        private void Listening()
        {
            while (!stop)
            {
                try
                {
                    Socket socket = socketServer.Accept();
                    Thread thread = new Thread(new ParameterizedThreadStart(OnSocket));
                    thread.Start(socket);
                }
                catch (Exception e)
                {
                    OnError(e);
                }
            }

            socketServer.Close();
            SocketApplicationComm.Debug("关闭服务器套接字!");
        }
Exemplo n.º 12
0
        internal T DoRequest <T>(int funcid, object param)
        {
            SOARedirectRequest request = new SOARedirectRequest();

            request.FuncId = funcid;
            if (param == null)
            {
                request.Param = null;
            }
            else
            {
                request.Param = EntityBufCore.Serialize(param);
            }

            Message msg = new Message((int)SOAMessageType.DoSOARedirectRequest);

            msg.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
            msg.MessageBuffer = EntityBufCore.Serialize(request);

            T result = SendMessageAnsy <T>(msg);

            return(result);
        }
Exemplo n.º 13
0
        public void StartRedirectService()
        {
            var localhost = System.Net.Dns.GetHostName();
            var addrs     = System.Net.Dns.GetHostAddresses(localhost);
            List <System.Net.IPAddress> bindips = new List <System.Net.IPAddress>();

            if (addrs != null && addrs.Length > 0)
            {
                foreach (var addr in addrs)
                {
                    if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        bindips.Add(addr);
                    }
                }
            }

            if (addrs.Length > 0)
            {
                int iport = 0;
                if (SupportTcpServiceRidrect && RedirectTcpServiceServer == null)
                {
                    int trytimes = 0;
                    while (true)
                    {
                        try
                        {
                            iport = SocketApplicationComm.GetIdelTcpPort();

                            RedirectTcpServiceServer = new ESBRedirectService(bindips.Select(p => p.ToString()).ToArray(), iport);
                            RedirectTcpServiceServer.DoResponseAction = DoResponse;
                            RedirectTcpServiceServer.StartServer();
                            break;
                        }
                        catch (Exception ex)
                        {
                            trytimes++;
                            if (trytimes >= 10)
                            {
                                OnError(new Exception("启动tcp直连服务端口失败,已尝试" + trytimes + "次,端口:" + iport, ex));
                                break;
                            }
                        }
                    }
                }

                if (SupportUDPServiceRedirect && this.RedirectUpdServiceServer == null)
                {
                    int trytimes = 0;
                    while (true)
                    {
                        try
                        {
                            iport = SocketApplicationComm.GetIdelUdpPort(iport);

                            RedirectUpdServiceServer = new ESBUDPService(bindips.Select(p => p.ToString()).ToArray(), iport);
                            RedirectUpdServiceServer.DoResponseAction = DoResponse;
                            RedirectUpdServiceServer.StartServer();
                            break;
                        }
                        catch (Exception ex)
                        {
                            trytimes++;
                            if (trytimes >= 10)
                            {
                                OnError(new Exception("启动udp直连服务端口失败,已尝试" + trytimes + "次,端口:" + iport, ex));
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 14
0
 public void BroadCast(Message message)
 {
     SocketApplicationComm.Broadcast(this.udpBCSocket, message);
 }
Exemplo n.º 15
0
 public void MultiCast(Message message)
 {
     SocketApplicationComm.MulitBroadcast(this.udpMCSocket, message);
 }
Exemplo n.º 16
0
        private void OnSocket(object obj)
        {
            Socket socket = (Socket)obj;

            socket.NoDelay           = true;
            socket.ReceiveBufferSize = 32000;
            socket.SendBufferSize    = 32000;
            IPEndPoint endPoint = (IPEndPoint)socket.RemoteEndPoint;

            Session appSocket = new Session();

            appSocket.IPAddress = endPoint.Address.ToString();
            appSocket.IsValid   = true;
            appSocket.SessionID = SocketApplicationComm.GetSeqNum();
            appSocket.Socket    = socket;

            while (appSocket.IsValid && appSocket.Socket.Connected)
            {
                try
                {
                    byte[] buff4 = new byte[4];
                    int    count = socket.Receive(buff4);

                    if (count != 4)
                    {
                        throw new SessionAbortException("接收数据出错。");
                    }

                    int dataLen = BitConverter.ToInt32(buff4, 0);

                    if (dataLen > MaxPackageLength)
                    {
                        throw new Exception("超过了最大字节数:" + MaxPackageLength);
                    }

                    MemoryStream ms           = new MemoryStream();
                    int          readLen      = 0;
                    byte[]       reciveBuffer = new byte[1024];

                    while (readLen < dataLen)
                    {
                        count    = socket.Receive(reciveBuffer, Math.Min(dataLen - readLen, reciveBuffer.Length), SocketFlags.None);
                        readLen += count;
                        ms.Write(reciveBuffer, 0, count);
                    }
                    var buffer = ms.ToArray();
                    ms.Close();

                    //搞成异步的
                    new Action <byte[], Session>((b, s) =>
                    {
                        Message message = EntityBufCore.DeSerialize <Message>(b);
                        FormApp(message, s);
                    }).BeginInvoke(buffer, appSocket, null, null);
                }
                catch (SessionAbortException exp)
                {
                    SocketApplicationComm.Debug(exp.Message);
                    break;
                }
                catch (SocketException exp)
                {
                    SocketApplicationComm.Debug(exp.Message);
                    break;
                }
                catch (Exception exp)
                {
                    SocketApplicationComm.Debug(exp.Message);
                    OnError(exp);
                }
            }

            socket.Close();
            SocketApplicationComm.Debug(string.Format("服务器关闭套接字:{0}", appSocket.SessionID));
        }
Exemplo n.º 17
0
        internal void DoTransferRequest(Session session, string msgTransactionID, SOARequest request)
        {
            session.BusinessTimeStamp = DateTime.Now;
            session.Tag = new Tuple <int, int>(request.ServiceNo, request.FuncId);

            SOAResponse resp   = new SOAResponse();
            Message     msgRet = new Message((int)SOAMessageType.DoSOAResponse);

            msgRet.MessageHeader.TransactionID = msgTransactionID;
            resp.IsSuccess = true;

            //调用本地的方法
            if (request.ServiceNo == 0)
            {
                try
                {
                    var obj = DoRequest(request.FuncId, request.Param);
                    resp.Result = EntityBuf.EntityBufCore.Serialize(obj);
                }
                catch (Exception ex)
                {
                    resp.IsSuccess = false;
                    resp.ErrMsg    = ex.Message;
                }

                msgRet.SetMessageBody(resp);
                session.SendMessage(msgRet);
            }
            else
            {
                //查询服务
                var serviceInfos = ServiceContainer.FindAll(p => p.ServiceNo.Equals(request.ServiceNo));
                if (serviceInfos == null || serviceInfos.Count == 0)
                {
                    resp.IsSuccess = false;
                    resp.ErrMsg    = string.Format("{0}服务未注册。", request.ServiceNo);
                }

                if (resp.IsSuccess)
                {
                    ESBServiceInfo serviceInfo = null;
                    if (serviceInfos.Count == 1)
                    {
                        serviceInfo = serviceInfos[0];
                    }
                    else
                    {
                        Random rd  = new Random();
                        var    idx = rd.Next(1, serviceInfos.Count + 1);
                        serviceInfo = serviceInfos[idx - 1];
                    }

                    try
                    {
                        if (DateTime.Now.Subtract(serviceInfo.Session.LastSessionTime).TotalSeconds > 30)
                        {
                            lock (LockObj)
                            {
                                ServiceContainer.Remove(serviceInfo);
                                serviceInfo.Session.Close();
                            }
                            serviceInfo = ServiceContainer.FindAll(p => p.ServiceNo.Equals(request.ServiceNo)).LastOrDefault();
                            if (serviceInfo == null)
                            {
                                throw new Exception(string.Format("{0}服务可能不可用,30秒无应答。", request.ServiceNo));
                            }
                        }

                        string             clientid        = session.SessionID;
                        SOATransferRequest transferrequest = new SOATransferRequest();
                        transferrequest.ClientId            = clientid;
                        transferrequest.FundId              = request.FuncId;
                        transferrequest.Param               = request.Param;
                        transferrequest.ClientTransactionID = msgTransactionID;

                        Message msg = new Message((int)SOAMessageType.DoSOATransferRequest);
                        msg.MessageHeader.TransactionID = SocketApplicationComm.GetSeqNum();
                        msg.SetMessageBody(transferrequest);

                        try
                        {
                            ConatinerLock.EnterWriteLock();
                            ClientSessionList.Add(msgTransactionID, session);
                        }
                        finally
                        {
                            ConatinerLock.ExitWriteLock();
                        }

                        if (serviceInfo.Session.SendMessage(msg))
                        {
                            //LogHelper.Instance.Debug(string.Format("发送SOA请求,请求序列:{0},服务号:{1},功能号:{2}",
                            //    msgTransactionID, request.ServiceNo, request.FuncId));
                            return;
                        }
                        else
                        {
                            try
                            {
                                ConatinerLock.EnterWriteLock();
                                ClientSessionList.Remove(msgTransactionID);
                            }
                            finally
                            {
                                ConatinerLock.ExitWriteLock();
                            }
                        }
                        //var result = SendMessageAnsy<byte[]>(serviceInfo.Session, msg);

                        //resp.Result = result;
                    }
                    catch (Exception ex)
                    {
                        OnError(ex);

                        resp.IsSuccess = false;
                        resp.ErrMsg    = ex.Message;
                    }
                }

                if (!resp.IsSuccess)
                {
                    msgRet.SetMessageBody(resp);
                    session.SendMessage(msgRet);
                }
            }
        }