AIO | BIO | NIO | Netty | |
---|---|---|---|---|
过程 | 异步,非阻塞 | 阻塞,来一个创建一个客户端 阻塞是在accept() | 不阻塞 | 1.boss 只接收 2.work 用来干活 3.group 告诉你这是一组的 |
open().bind() .accpet() | ss.accept() | //1.添加客户端 //2.遍历链表 | ||
new thread() | clients.add() | |||
AsynchronousServerSocketChannel AsynchronousSocketChannel | ServerSocket Socket | ServerSocketChannel Selector | EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); | |
数据处理handle() | ByteBuffer buffer = ByteBuffer.allocate(1024); | byte[] bytes = new byte[1024]; | ByteBuffer buffer = ByteBuffer.allocate(512); | ByteBuf buf = (ByteBuf)msg; |
BIO:
public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(9090);//1599
System.out.println("step1:new ServerSocket(9090)");
while(true)
{
final Socket client=server.accept();//阻塞
System.out.println("step2:client\t"+client.getPort());
new Thread(new Runnable()//PID 1676
{
public void run() {
InputStream in = null;
try {
in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while (true)
{
String dataline = reader.readLine();
if (null != dataline)
{
System.out.println(dataline);
} else
{
client.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}});
}
}
}
NIO
public class SocketNIO
{
Public static void main()
{
LinkedList<SocketChannel> clients =new LinkedList<>();
ServerSocketChannel ss=ServerSocketChannel.open();
ss.bind(new InetSocketAddress(9090));
ss.configureBlocking(false);
//1.添加客户端
//2.遍历链表
while(true)
{
//接收客户端连接
SocketChannel client=ss.accept();
if(client==null)
{
}
else
{
client.configureBlocking(false);
int port=client.socket().getPort();
clients.add(client);
}
ByteBuffer buffer=ByteBuffer.allocateDirect(4096);
for(SocketChannel d:clients)
{
int num=c.read(buffer);//不会阻塞 有可能读到有可能没读到。0没读到,-1断开,>0 读到了数据
if(num>0){
buffer.filp();
byte[] aaa=new byte[buffer.limit()];
buffer.get(aaa);
String b=new String(aaa);
buffer.clear();
}
}
}
}
}