/// <summary> /// 连接至服务器。 /// </summary> /// <param name="endpoint">服务器终结点。</param> public void Connect(IPEndPoint endpoint) { //判断是否已连接 if (IsConnected) { throw new InvalidOperationException("已连接至服务器。"); } if (endpoint == null) { throw new ArgumentNullException("endpoint"); } //锁定自己,避免多线程同时操作 lock (this) { SocketAsyncState state = new SocketAsyncState(); //Socket异步连接 Socket.BeginConnect(endpoint, EndConnect, state).AsyncWaitHandle.WaitOne(); //等待异步全部处理完成 while (!state.Completed) { Thread.Sleep(1); } } }
protected void EndReceive(IAsyncResult result) { SocketAsyncState state = (SocketAsyncState)result.AsyncState; //接收到的数据 byte[] data = Handler.EndReceive(result); //如果数据长度为0,则断开Socket连接 if (data.Length == 0) { Disconnected(true); return; } //再次开始接收数据 Handler.BeginReceive(Stream, EndReceive, state); //引发接收完成事件 if (ReceiveCompleted != null) { ReceiveCompleted(this, new SocketEventArgs(this, SocketAsyncOperation.Receive) { Data = data }); } }