Beispiel #1
0
        /*****************************************************************************
         *
         *    说明:
         *    下面的三个模块代码指示了如何接收数据,如何发送数据,如何连接网络
         *
         ********************************************************************************/

        #region Reveive Content

        /// <summary>
        /// 接收固定长度的字节数组
        /// </summary>
        /// <remarks>
        /// Receive Special Length Bytes
        /// </remarks>
        /// <param name="socket">网络通讯的套接字</param>
        /// <param name="length">准备接收的数据长度</param>
        /// <returns>包含了字节数据的结果类</returns>
        protected OperateResult <byte[]> Receive(Socket socket, int length)
        {
            if (length == 0)
            {
                return(OperateResult.CreateSuccessResult(new byte[0]));
            }

            var result      = new OperateResult <byte[]>( );
            var receiveDone = new ManualResetEvent(false);
            var state       = new StateObject(length);

            try
            {
                state.WaitDone   = receiveDone;
                state.WorkSocket = socket;

                // Begin receiving the data from the remote device.
                socket.BeginReceive(state.Buffer, state.AlreadyDealLength,
                                    state.DataLength - state.AlreadyDealLength, SocketFlags.None,
                                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception ex)
            {
                // 发生了错误,直接返回
                LogNet?.WriteException(ToString( ), ex);
                result.Message = ex.Message;
                receiveDone.Close( );
                socket?.Close( );
                return(result);
            }



            // 等待接收完成,或是发生异常
            receiveDone.WaitOne( );
            receiveDone.Close( );



            // 接收数据失败
            if (state.IsError)
            {
                socket?.Close( );
                result.Message = state.ErrerMsg;
                return(result);
            }


            // 远程关闭了连接
            if (state.IsClose)
            {
                result.IsSuccess = true;
                result.Message   = "远程关闭了连接";
                socket?.Close( );
                return(result);
            }


            // 正常接收到数据
            result.Content   = state.Buffer;
            result.IsSuccess = true;
            state.Clear( );
            state = null;
            return(result);
        }
Beispiel #2
0
        /*****************************************************************************
         *
         *    说明:
         *    下面的三个模块代码指示了如何接收数据,如何发送数据,如何连接网络
         *
         ********************************************************************************/

        #region Reveive Content

        /// <summary>
        /// 接收固定长度的字节数组
        /// </summary>
        /// <remarks>
        /// Receive Special Length Bytes
        /// </remarks>
        /// <param name="socket">网络通讯的套接字</param>
        /// <param name="length">准备接收的数据长度</param>
        /// <returns>包含了字节数据的结果类</returns>
        protected OperateResult <byte[]> Receive(Socket socket, int length)
        {
            if (length == 0)
            {
                return(OperateResult.CreateSuccessResult(new byte[0]));
            }

            //try
            //{
            //    return OperateResult.CreateSuccessResult( NetSupport.ReadBytesFromSocket( socket, length ) );
            //}
            //catch(Exception ex)
            //{
            //    return new OperateResult<byte[]>( ex.Message );
            //}

//#if NET35

            var            result      = new OperateResult <byte[]>( );
            var            receiveDone = new ManualResetEvent(false);
            AutoResetEvent autoReset   = new AutoResetEvent(false);
            var            state       = new StateObject(length);

            try
            {
                state.WaitDone   = receiveDone;
                state.WorkSocket = socket;

                // Begin receiving the data from the remote device.
                socket.BeginReceive(state.Buffer, state.AlreadyDealLength,
                                    state.DataLength - state.AlreadyDealLength, SocketFlags.None,
                                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception ex)
            {
                // 发生了错误,直接返回
                LogNet?.WriteException(ToString( ), ex);
                result.Message = ex.Message;
                receiveDone.Close( );
                socket?.Close( );
                return(result);
            }



            // 等待接收完成,或是发生异常
            receiveDone.WaitOne( );
            receiveDone.Close( );



            // 接收数据失败
            if (state.IsError)
            {
                socket?.Close( );
                result.Message = state.ErrerMsg;
                return(result);
            }


            // 远程关闭了连接
            if (state.IsClose)
            {
                // result.IsSuccess = true;
                result.Message = StringResources.Language.RemoteClosedConnection;
                socket?.Close( );
                return(result);
            }


            // 正常接收到数据
            result.Content   = state.Buffer;
            result.IsSuccess = true;
            state.Clear( );
            state = null;
            return(result);

//#else
            //SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs( );
            //byte[] buffer = new byte[length];
            //eventArgs.SetBuffer( buffer, 0, length );
            //int receiveCount = 0;
            //while (true)
            //{
            //    socket.ReceiveAsync( eventArgs );
            //    receiveCount += eventArgs.BytesTransferred;
            //    if (receiveCount == length) break;
            //}
            //return OperateResult.CreateSuccessResult( buffer );
//#endif
        }
Beispiel #3
0
        /// <summary>
        /// 发送消息给套接字,直到完成的时候返回
        /// </summary>
        /// <param name="socket">网络套接字</param>
        /// <param name="data">字节数据</param>
        /// <returns>发送是否成功的结果</returns>
        protected OperateResult Send(Socket socket, byte[] data)
        {
            if (data == null)
            {
                return(OperateResult.CreateSuccessResult( ));
            }

            if (UseSynchronousNet)
            {
                try
                {
                    socket.Send(data);
                    return(OperateResult.CreateSuccessResult( ));
                }
                catch (Exception ex)
                {
                    socket?.Close( );
                    LogNet?.WriteException("Send", ex);
                    return(new OperateResult <byte[]>(ex.Message));
                }
            }

            OperateResult    result   = new OperateResult( );
            ManualResetEvent sendDone = null;
            StateObject      state    = null;

            try
            {
                sendDone = new ManualResetEvent(false);
                state    = new StateObject(data.Length);
            }
            catch (Exception ex)
            {
                return(new OperateResult(ex.Message));
            }

            try
            {
                state.WaitDone   = sendDone;
                state.WorkSocket = socket;
                state.Buffer     = data;

                socket.BeginSend(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength,
                                 SocketFlags.None, new AsyncCallback(SendCallBack), state);
            }
            catch (Exception ex)
            {
                // 发生了错误,直接返回
                LogNet?.WriteException(ToString( ), ex);
                result.Message = ex.Message;
                socket?.Close( );
                sendDone.Close( );
                return(result);
            }

            // 等待发送完成
            sendDone.WaitOne( );
            sendDone.Close( );

            if (state.IsError)
            {
                socket.Close( );
                result.Message = state.ErrerMsg;
                return(result);
            }

            state.Clear( );
            state            = null;
            result.IsSuccess = true;
            result.Message   = StringResources.Language.SuccessText;

            return(result);
        }
Beispiel #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
            {
                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);
            }
        }
Beispiel #5
0
        /*****************************************************************************
         *
         *    说明:
         *    下面的三个模块代码指示了如何接收数据,如何发送数据,如何连接网络
         *
         ********************************************************************************/

        #region Reveive Content

        /// <summary>
        /// 接收固定长度的字节数组
        /// </summary>
        /// <remarks>
        /// Receive Special Length Bytes
        /// </remarks>
        /// <param name="socket">网络通讯的套接字</param>
        /// <param name="length">准备接收的数据长度</param>
        /// <returns>包含了字节数据的结果类</returns>
        protected OperateResult <byte[]> Receive(Socket socket, int length)
        {
            if (length == 0)
            {
                return(OperateResult.CreateSuccessResult(new byte[0]));
            }

            if (UseSynchronousNet)
            {
                try
                {
                    byte[] data = NetSupport.ReadBytesFromSocket(socket, length);
                    return(OperateResult.CreateSuccessResult(data));
                }
                catch (Exception ex)
                {
                    socket?.Close( );
                    LogNet?.WriteException(ToString( ), "Receive", ex);
                    return(new OperateResult <byte[]>(ex.Message));
                }
            }

            OperateResult <byte[]> result      = new OperateResult <byte[]>( );
            ManualResetEvent       receiveDone = null;
            StateObject            state       = null;

            try
            {
                receiveDone = new ManualResetEvent(false);
                state       = new StateObject(length);
            }
            catch (Exception ex)
            {
                return(new OperateResult <byte[]>(ex.Message));
            }


            try
            {
                state.WaitDone   = receiveDone;
                state.WorkSocket = socket;

                // Begin receiving the data from the remote device.
                socket.BeginReceive(state.Buffer, state.AlreadyDealLength,
                                    state.DataLength - state.AlreadyDealLength, SocketFlags.None,
                                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception ex)
            {
                // 发生了错误,直接返回
                LogNet?.WriteException(ToString( ), ex);
                result.Message = ex.Message;
                receiveDone.Close( );
                socket?.Close( );
                return(result);
            }



            // 等待接收完成,或是发生异常
            receiveDone.WaitOne( );
            receiveDone.Close( );



            // 接收数据失败
            if (state.IsError)
            {
                socket?.Close( );
                result.Message = state.ErrerMsg;
                return(result);
            }


            // 远程关闭了连接
            if (state.IsClose)
            {
                // result.IsSuccess = true;
                result.Message = StringResources.Language.RemoteClosedConnection;
                socket?.Close( );
                return(result);
            }


            // 正常接收到数据
            result.Content   = state.Buffer;
            result.IsSuccess = true;
            state.Clear( );
            state = null;
            return(result);
        }