Exemplo n.º 1
0
        public async Task Send(TcpDuplexListener listener, Func <List <TcpDuplexListenerConnection>, Task <TcpDuplexDataExecuteResult> > dataExecute)
        {
            var connections = GetConnections();

            if (_start)
            {
                var byteResult = await dataExecute(connections);

                if (byteResult.ResponseData != null && byteResult.ResponseData.Length > 0)
                {
                    List <TcpDuplexAcceptContext> sendContexts = null;
                    if (byteResult.ResponseAll)
                    {
                        sendContexts = GetAllAcceptContext();
                    }
                    else
                    {
                        sendContexts = GetAcceptContext(byteResult.ResponseConnections);
                    }

                    if (sendContexts != null)
                    {
                        foreach (var itemSendContext in sendContexts)
                        {
                            await itemSendContext.ReceiveSemaphore.WaitAsync();

                            itemSendContext.SocketAsyncEventArgs.SetBuffer(byteResult.ResponseData, 0, byteResult.ResponseData.Length);

                            try
                            {
                                var willRaiseEvent = itemSendContext.SocketAsyncEventArgs.AcceptSocket.SendAsync(itemSendContext.SocketAsyncEventArgs);
                                if (!willRaiseEvent)
                                {
                                    await ProcessSend(itemSendContext.SocketAsyncEventArgs);
                                }
                            }
                            catch (Exception ex)
                            {
                                CloseClientSocket(itemSendContext.SocketAsyncEventArgs);
                                await AddLog($"Send Error,message:{ex.Message},stack:{ex.StackTrace}", DateTime.UtcNow);

                                LoggerHelper.LogError(LogCategoryName, $"TcpDuplexListener {_listener.Name},Send Error,message:{ex.Message},stack:{ex.StackTrace}");
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
        public async Task Stop(TcpDuplexListener listener)
        {
            _listener = listener;
            if (_start)
            {
                try
                {
                    _listenSocket.Close();
                }
                catch
                {
                }

                _listenSocket = null;

                TcpDuplexAcceptContext itemContext;

                List <TcpDuplexAcceptContext> returnList = new List <TcpDuplexAcceptContext>();



                foreach (var item in _tcpDuplexAcceptContextPool.Items)
                {
                    itemContext = (TcpDuplexAcceptContext)item.Value;

                    lock (itemContext.LockObj)
                    {
                        itemContext.Status = -1;
                    }
                    itemContext.ReleaseReceiveSemaphore();
                    itemContext.ReleaseSendSemaphore();
                }
                _start = false;
                ReleaseAcceptSemaphore();
            }

            await Task.FromResult(0);
        }
Exemplo n.º 3
0
        public async Task Start(TcpDuplexListener listener)
        {
            if (!_tcpDuplexDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out IFactory <ITcpDuplexDataExecute> tcpDataExecuteFactory))
            {
                lock (_tcpDuplexDataExecuteFactories)
                {
                    Type tcpDataExecuteFactoryType = Type.GetType(_listener.ExecuteDataFactoryType);

                    if (!_tcpDuplexDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out tcpDataExecuteFactory))
                    {
                        object objTcpDataExecuteFactory;
                        if (_listener.ExecuteDataFactoryTypeUseDI == true)
                        {
                            //通过DI容器创建
                            objTcpDataExecuteFactory = DIContainerContainer.Get(tcpDataExecuteFactoryType);
                        }
                        else
                        {
                            //通过反射创建
                            objTcpDataExecuteFactory = tcpDataExecuteFactoryType.Assembly.CreateInstance(tcpDataExecuteFactoryType.FullName);
                        }

                        if (!(objTcpDataExecuteFactory is IFactory <ITcpDataExecute>))
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.TcpDuplexDataExecuteTypeError,
                                DefaultFormatting = "双工Tcp监听{0}中,数据处理的工厂类型{1}未实现接口IFactory<ITcpDuplexDataExecute>",
                                ReplaceParameters = new List <object>()
                                {
                                    _listener.Name, _listener.ExecuteDataFactoryType
                                }
                            };

                            throw new UtilityException((int)Errors.TcpDuplexDataExecuteTypeError, fragment);
                        }

                        tcpDataExecuteFactory = (IFactory <ITcpDuplexDataExecute>)objTcpDataExecuteFactory;
                        _tcpDuplexDataExecuteFactories.Add(_listener.ExecuteDataFactoryType, tcpDataExecuteFactory);
                    }
                }
            }



            _listener = listener;
            if (!_start)
            {
                //设置监听Socket
                IPEndPoint localPoint = new IPEndPoint(IPAddress.Any, listener.Port);
                _listenSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                _listenSocket.Bind(localPoint);
                _listenSocket.Listen(listener.MaxConcurrencyCount);


                //设置连接参数池
                _tcpDuplexAcceptContextPool = new Pool <TcpDuplexAcceptContext>($"TcpDuplexListener-{listener.Name}-AcceptContexts",
                                                                                null,
                                                                                null,
                                                                                null,
                                                                                null,
                                                                                async() =>
                {
                    var connection = new TcpDuplexListenerConnection(Guid.NewGuid(), await tcpDataExecuteFactory.Create().GetInitExtensionInfo());


                    var context = new TcpDuplexAcceptContext(connection.ID)
                    {
                        ListenSocket = _listenSocket,
                        Connection   = connection
                    };

                    var acceptEventArg = new SocketAsyncEventArgs()
                    {
                        UserToken = context
                    };
                    acceptEventArg.Completed    += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                    context.SocketAsyncEventArgs = acceptEventArg;

                    return(await Task.FromResult(context));
                },
                                                                                async(item) =>
                {
                    return(await Task.FromResult(true));
                },
                                                                                null,
                                                                                null
                                                                                , listener.MaxConcurrencyCount);


                _start = true;



                //启动定时检查Tcp连接
                var t = Task.Run(async() =>
                {
                    while (_start)
                    {
                        try
                        {
                            await ValidateConnection();
                        }
                        catch (Exception ex)
                        {
                            LoggerHelper.LogError(LogCategoryName, $"TcpDuplexListener {_listener.Name},ValidateConnection Error,message:{ex.Message},stack:{ex.StackTrace}");
                        }

                        System.Threading.Thread.Sleep(100);
                    }
                });


                await StartAccept(_listenSocket);
            }
        }