예제 #1
0
        /// <summary>
        /// 开始接收
        /// </summary>
        /// <param name="stream">Socket网络流</param>
        /// <param name="callback">回调函数</param>
        /// <param name="state">自定义状态</param>
        /// <returns>异步结果</returns>
        public IAsyncResult BeginReceive(Stream stream, AsyncCallback callback, object state)
        {
            //stream不能为null
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            //回调函数不能为null
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            //stream异常
            if (!stream.CanRead)
            {
                throw new ArgumentException("stream不支持读取。");
            }

            SocketAsyncResult result = new SocketAsyncResult(state);

            //初始化SocketHandlerState
            SocketHandlerState shs = new SocketHandlerState();

            shs.Data          = new byte[READ_BUFFER];
            shs.AsyncResult   = result;
            shs.Stream        = stream;
            shs.AsyncCallBack = callback;
            shs.Completed     = true;
            try
            {
                stream.BeginRead(shs.Data, 0, READ_BUFFER, EndRead, shs);
            }
            catch
            {
                result.CompletedSynchronously = true;
                shs.Data      = new byte[0];
                shs.Completed = false;
                lock (StateSet)
                    StateSet.Add(result, shs);
                ((AutoResetEvent)result.AsyncWaitHandle).Set();
                callback(result);
            }


            return(result);
        }
예제 #2
0
        public void EndRead(IAsyncResult ar)
        {
            SocketHandlerState state = (SocketHandlerState)ar.AsyncState;

            if (state.Data[0].Equals(0))
            {
                lock (StateSet)
                    StateSet.Add(state.AsyncResult, state);
                //设定接收到的数据位空byte数组
                state.Data = new byte[0];
                //允许等待线程继续
                ((AutoResetEvent)state.AsyncResult.AsyncWaitHandle).Set();
                //执行异步回调函数
                state.AsyncCallBack(state.AsyncResult);
                return;
            }
            state.Completed = true;
            lock (StateSet)
                StateSet.Add(state.AsyncResult, state);
            ((AutoResetEvent)state.AsyncResult.AsyncWaitHandle).Set();
            state.AsyncCallBack(state.AsyncResult);
        }
예제 #3
0
        //stream异步结束写入
        private void EndWrite(IAsyncResult ar)
        {
            SocketHandlerState state = (SocketHandlerState)ar.AsyncState;

            //锁定StateSet
            lock (StateSet)
                StateSet.Add(state.AsyncResult, state);

            try
            {
                state.Stream.EndWrite(ar);
            }
            catch
            {
                //出现Socket异常,发送失败
                state.Completed = false;
                //允许等待线程继续
                ((AutoResetEvent)state.AsyncResult.AsyncWaitHandle).Set();
                //执行异步回调函数
                state.AsyncCallBack(state.AsyncResult);
                return;
            }
            //发送成功
            state.Completed = true;
            //允许等待线程继续
            ((AutoResetEvent)state.AsyncResult.AsyncWaitHandle).Set();
            //执行异步回调函数
            state.AsyncCallBack(state.AsyncResult);

            //锁定SendQueue
            lock (SendQueue)
            {
                SocketHandlerState prepare = null;
                //移除当前发送完成的数据
                SendQueue.Remove(state);
                //如果SendQueue还有数据存在,则继续发送
                if (SendQueue.Count > 0)
                {
                    prepare = SendQueue[0];
                }
                if (prepare != null)
                {
                    //获取数据长度
                    //ushort的最大值为65535
                    //转换为byte[]长度为2
                    //var dataLength = BitConverter.GetBytes((ushort)prepare.Data.Length);
                    //向对方发送长度为2的头信息,表示接下来要发送的数据长度
                    try
                    {
                        //prepare.Stream.Write(dataLength, 0, dataLength.Length);
                        //开始异步发送数据
                        prepare.Stream.BeginWrite(prepare.Data, 0, prepare.Data.Length, EndWrite, prepare).AsyncWaitHandle.WaitOne();
                    }
                    catch
                    {
                        prepare.Completed = false;
                        ((AutoResetEvent)prepare.AsyncResult.AsyncWaitHandle).Set();
                        prepare.AsyncCallBack(prepare.AsyncResult);
                    }
                }
            }
        }
예제 #4
0
        /// <summary>
        /// 开始发送
        /// </summary>
        /// <param name="data">要发送的数据</param>
        /// <param name="offset">数据偏移</param>
        /// <param name="count">发送长度</param>
        /// <param name="stream">Socket网络流</param>
        /// <param name="callback">回调函数</param>
        /// <param name="state">自定义状态</param>
        /// <returns>异步结果</returns>
        public IAsyncResult BeginSend(byte[] data, int offset, int count, Stream stream, AsyncCallback callback, object state)
        {
            //data不能为null
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            //offset不能小于0和超过data长度
            if (offset > data.Length || offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            //count不能大于65535
            if (count <= 0 || count > data.Length - offset || count > ushort.MaxValue)
            {
                throw new ArgumentOutOfRangeException("count");
            }
            //stream不能为null
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            //回调函数不能为null
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            //stream异常
            if (!stream.CanWrite)
            {
                throw new ArgumentException("stream不支持写入。");
            }

            SocketAsyncResult result = new SocketAsyncResult(state);

            //初始化SocketHandlerState
            SocketHandlerState shs = new SocketHandlerState();

            shs.Data          = data;
            shs.AsyncResult   = result;
            shs.Stream        = stream;
            shs.AsyncCallBack = callback;
            shs.DataLength    = 0;

            //锁定SendQueue
            //避免多线程同时发送数据
            lock (SendQueue)
            {
                //添加状态
                SendQueue.Add(shs);
                //如果SendQueue数量大于1,则表示有数据尚未发送完成
                if (SendQueue.Count > 1)
                {
                    return(result);
                }
            }

            ////获取数据长度
            ////ushort的最大值为65535
            ////转换为byte[]长度为2
            //var dataLength = BitConverter.GetBytes((ushort)data.Length);
            ////向对方发送长度为2的头信息,表示接下来要发送的数据长度
            //try
            //{
            //    stream.Write(dataLength, 0, dataLength.Length);
            //}
            //catch
            //{
            //    result.CompletedSynchronously = true;
            //    shs.Completed = false;
            //    lock (StateSet)
            //        StateSet.Add(result, shs);
            //    ((AutoResetEvent)result.AsyncWaitHandle).Set();
            //    callback(result);
            //}
            //开始异步发送数据
            try
            {
                stream.BeginWrite(shs.Data, 0, shs.Data.Length, EndWrite, shs);
            }
            catch
            {
                result.CompletedSynchronously = true;
                shs.Completed = false;
                lock (StateSet)
                    StateSet.Add(result, shs);
                ((AutoResetEvent)result.AsyncWaitHandle).Set();
                callback(result);
            }
            return(result);
        }