/// <summary> /// 从socket中读取数据 /// </summary> /// <param name="ar"></param> private void ReadProxy(IAsyncResult ar) { HPServerSocket serverSocket = ar.AsyncState as HPServerSocket; if (serverSocket == null) { return; } try { int bytesRead = serverSocket.Socket.EndReceive(ar); if (bytesRead == 0) { //客户端已经关闭 } else { //读取到了数据 //处理数据 //重新接收数据 serverSocket.Socket.BeginReceive(serverSocket.Buffer, 0, serverSocket.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveProxy), serverSocket); } } catch (SocketException sex) { } catch (Exception) { } }
/// <summary> /// 接收处理 /// </summary> /// <param name="obj"></param> private void ReceiveProxy(object obj) { while (isRunning) { HPServerSocket curSocket = null; try { if (conQueue.TryDequeue(out curSocket)) { //获取到内容 curSocket.Socket.BeginReceive(curSocket.Buffer, 0, curSocket.Buffer.Length, SocketFlags.None, new AsyncCallback(ReadProxy), curSocket); } else { Thread.Sleep(100); } } catch (SocketException sex) { } catch (Exception ex) { } } }
/// <summary> /// 监听是否有新连接接入 /// </summary> private void Listen() { try { tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Server.SendTimeout = 5000; tcpListener.Server.ReceiveTimeout = 5000; tcpListener.Start(backlog); isRunning = true; //通知主线程创建完毕 resetEvent.Set(); //休眠 Thread.Sleep(200); while (isRunning) { try { if (!tcpListener.Pending()) { Thread.Sleep(10); continue; } //AcceptSocket是阻塞的,直到有连接来到 Socket socket = tcpListener.AcceptSocket(); #region 开始处理连接 HPServerSocket item = new HPServerSocket(socket); conQueue.Enqueue(item); conBag.Add(item); #endregion } catch (SocketException sex) { } catch (Exception) { } } } catch (Exception ex) { isRunning = false; //通知主线程创建完毕 resetEvent.Set(); } }