private void ReceiveCb(IAsyncResult ar) { Conn conn = (Conn)ar.AsyncState; try { //获取接受的字节数 int count = conn.socket.EndReceive(ar); if (count <= 0) { Console.WriteLine("收到[" + conn.GetAdress() + "]断开连接"); conn.Close(); return; } //数据处理 //string str = System.Text.Encoding.UTF8.GetString(conn.readBuff, 0, count); conn.buffCount += count; ProcessData(conn); conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn); } catch (Exception e) { Console.WriteLine("收到[" + conn.GetAdress() + "]断开连接" + e.Message); conn.Close(); } }
//与客户端建立链接 private void AcceptCb(IAsyncResult ar) { try { Socket clientSocket = socket.EndAccept(ar); int index = NewIndex(); if (index < 0) { clientSocket.Close(); Console.WriteLine("[警告]连接池已满"); } else { Conn conn = conns[index]; conn.Init(clientSocket); Console.WriteLine("客户端连接[" + conn.GetAdress() + "]"); conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn); } socket.BeginAccept(AcceptCb, null); } catch (Exception e) { Console.WriteLine("AcceptCb失败:" + e.Message); } }
private void AcceptCb(IAsyncResult ar) { try { Socket socket = listenfd.EndAccept(ar); int index = NewIndex(); if (index < 0) { socket.Close(); Console.Write("[警告]连接已满"); } else { Conn conn = conns[index]; conn.Init(socket); string adr = conn.GetAddr(); Console.WriteLine("客户端连接[" + adr + "]conn池ID:" + index); conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn); listenfd.BeginAccept(AcceptCb, null); } } catch (Exception e) { Console.WriteLine("AcceptCb失败:" + e.Message); } }
private void ReceiveCb(IAsyncResult ar) { Conn conn = (Conn)ar.AsyncState; lock (conn) { try { int count = conn.socket.EndReceive(ar); if (count <= 0) { return; } conn.buffCount += count; ProcessData(conn); conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn); } catch { } } }