/// <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) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException("stream can not read"); } if (callback == null) { throw new ArgumentNullException("callback"); } SocketAsyncResult result = new SocketAsyncResult(state); SocketHandlerState shs = new SocketHandlerState(); //初始化SocketHandlerState shs.Data = new byte[1024]; shs.Stream = stream; shs.Completed = true; shs.AsyncResult = result; shs.AsyncCallBack = callback; //开始异步接收数据,包含接收的数据长度 try { stream.BeginRead(shs.Data, 0, 1024, EndRead, shs); } catch { result.CompletedSynchronously = true; shs.Data = new byte[0]; shs.DataLength = 0; shs.Completed = false; lock (StateSet) StateSet.Add(result, shs); ((AutoResetEvent)result.AsyncWaitHandle).WaitOne(); callback(result); } return(result); }
/// <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) { if (data == null) { throw new ArgumentNullException("data"); } if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count <= 0 || count > data.Length - offset || count > ushort.MaxValue) { throw new ArgumentOutOfRangeException("count"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanWrite) { throw new ArgumentException("stream can not write"); } if (callback == null) { throw new ArgumentNullException("callback"); } SocketAsyncResult result = new SocketAsyncResult(state); SocketHandlerState shs = new SocketHandlerState(); //初始化SocketHandlerState shs.Data = data; shs.DataLength = 0; shs.Stream = stream; shs.Completed = true; shs.AsyncResult = result; shs.AsyncCallBack = callback; lock (SendQueue) //锁定SendQueue,避免多线程同时发送数据 { SendQueue.Add(shs); //添加状态 if (SendQueue.Count > 1) //表示尚有数据未发送完成 { return(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); }