Пример #1
0
        /// <summary>
        /// 发送一个异步的数据信息,该方式在NET35里是不可用的。
        /// </summary>
        /// <param name="socket">网络的套接字</param>
        /// <param name="data">数据内容</param>
        /// <returns>是否发送成功</returns>
        protected OperateResult SendAsync(Socket socket, byte[] data)
        {
            if (data == null)
            {
                return(OperateResult.CreateSuccessResult( ));
            }

            StateObjectAsync <bool> state = null;

            try
            {
                state     = new StateObjectAsync <bool>(data.Length);
                state.Tcs = new TaskCompletionSource <bool>( );
            }
            catch (Exception ex)
            {
                return(new OperateResult(ex.Message));
            }

            state.WorkSocket = socket;
            state.Buffer     = data;

            try
            {
                socket.BeginSend(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength,
                                 SocketFlags.None, new AsyncCallback(SendAsyncCallBack), state);
                bool boolResult = state.Tcs.Task.Result;
                return(OperateResult.CreateSuccessResult( ));
            }
            catch (Exception ex)
            {
                return(new OperateResult(ex.Message));
            }
        }
        /// <summary>
        /// 接收固定长度的字节数组
        /// </summary>
        /// <remarks>
        /// Receive Special Length Bytes
        /// </remarks>
        /// <param name="socket">网络通讯的套接字</param>
        /// <param name="length">准备接收的数据长度</param>
        /// <returns>包含了字节数据的结果类</returns>
        protected OperateResult <byte[]> ReceiveAsync(Socket socket, int length)
        {
            if (length <= 0)
            {
                return(OperateResult.CreateSuccessResult(new byte[0]));
            }

            var state = new StateObjectAsync <byte[]>(length);

            state.Tcs        = new TaskCompletionSource <byte[]>( );
            state.WorkSocket = socket;

            try
            {
                socket.BeginReceive(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength,
                                    SocketFlags.None, new AsyncCallback(ReceiveAsyncCallback), state);
                byte[] byteResult = state.Tcs.Task.Result;
                if (byteResult == null)
                {
                    socket?.Close( );
                    return(new OperateResult <byte[]>(StringResources.Language.RemoteClosedConnection));
                }

                state.Clear( );
                state = null;
                return(OperateResult.CreateSuccessResult(byteResult));
            }
            catch (Exception ex)
            {
                return(new OperateResult <byte[]>(ex.Message));
            }
        }
        private OperateResult <Socket> ConnectAsync(IPEndPoint endPoint, int timeOut)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var state  = new StateObjectAsync <Socket>( );

            state.Tcs        = new TaskCompletionSource <Socket>( );
            state.WorkSocket = socket;

            // timeout check
            HslTimeOut connectTimeout = new HslTimeOut( )
            {
                WorkSocket = socket,
                DelayTime  = timeOut
            };

            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout);

            try
            {
                socket.BeginConnect(endPoint, new AsyncCallback(ConnectAsyncCallBack), state);
                socket = state.Tcs.Task.Result;
                return(OperateResult.CreateSuccessResult(socket));
            }
            catch (Exception ex)
            {
                return(new OperateResult <Socket>(ex.Message));
            }
        }
Пример #4
0
        /// <summary>
        /// 创建一个新的socket对象并连接到远程的地址
        /// </summary>
        /// <param name="endPoint">连接的目标终结点</param>
        /// <param name="timeOut">连接的超时时间</param>
        /// <returns>返回套接字的封装结果对象</returns>
        /// <example>
        /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Core\NetworkBase.cs" region="CreateSocketAndConnectExample" title="创建连接示例" />
        /// </example>
        protected OperateResult <Socket> CreateSocketAndConnect(IPEndPoint endPoint, int timeOut)
        {
            if (UseSynchronousNet)
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    HslTimeOut connectTimeout = new HslTimeOut( )
                    {
                        WorkSocket = socket,
                        DelayTime  = timeOut
                    };
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout);
                    socket.Connect(endPoint);
                    connectTimeout.IsSuccessful = true;

                    return(OperateResult.CreateSuccessResult(socket));
                }
                catch (Exception ex)
                {
                    socket?.Close( );
                    LogNet?.WriteException("CreateSocketAndConnect", ex);
                    return(new OperateResult <Socket>(ex.Message));
                }
            }
            else
            {
#if NET35
                OperateResult <Socket> result      = new OperateResult <Socket>( );
                ManualResetEvent       connectDone = null;
                StateObject            state       = null;
                try
                {
                    connectDone = new ManualResetEvent(false);
                    state       = new StateObject( );
                }
                catch (Exception ex)
                {
                    return(new OperateResult <Socket>(ex.Message));
                }


                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 超时验证的信息
                HslTimeOut connectTimeout = new HslTimeOut( )
                {
                    WorkSocket = socket,
                    DelayTime  = timeOut
                };
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout);

                try
                {
                    state.WaitDone   = connectDone;
                    state.WorkSocket = socket;
                    socket.BeginConnect(endPoint, new AsyncCallback(ConnectCallBack), state);
                }
                catch (Exception ex)
                {
                    // 直接失败
                    connectTimeout.IsSuccessful = true;                                     // 退出线程池的超时检查
                    LogNet?.WriteException(ToString( ), ex);                                // 记录错误日志
                    socket.Close( );                                                        // 关闭网络信息
                    connectDone.Close( );                                                   // 释放等待资源
                    result.Message = StringResources.Language.ConnectedFailed + ex.Message; // 传递错误消息
                    return(result);
                }



                // 等待连接完成
                connectDone.WaitOne( );
                connectDone.Close( );
                connectTimeout.IsSuccessful = true;

                if (state.IsError)
                {
                    // 连接失败
                    result.Message = StringResources.Language.ConnectedFailed + state.ErrerMsg;
                    socket?.Close( );
                    return(result);
                }


                result.Content   = socket;
                result.IsSuccess = true;
                state.Clear( );
                state = null;
                return(result);
#else
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var state  = new StateObjectAsync <Socket>( );
                state.Tcs        = new TaskCompletionSource <Socket>( );
                state.WorkSocket = socket;

                // timeout check
                HslTimeOut connectTimeout = new HslTimeOut( )
                {
                    WorkSocket = socket,
                    DelayTime  = timeOut
                };
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout);

                try
                {
                    socket.BeginConnect(endPoint, new AsyncCallback(ConnectAsyncCallBack), state);
                    socket = state.Tcs.Task.Result;
                    return(OperateResult.CreateSuccessResult(socket));
                }
                catch (Exception ex)
                {
                    return(new OperateResult <Socket>(ex.Message));
                }
#endif
            }
        }