Netty-NIO线程模型
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
IO模型基本说明
BIO:
线程模型图
代码实例
/**
* @Author qrn
* @Date 2021/5/9 下午9:20
* @Version 1.0
* @blog https://blog.csdn.net/qq_41971087
* 实现一个简单的http服务:
*/
public class HttpServiceTest {
public static void main(String[] args) throws IOException{
//创建一个 ServerSocket 绑定8801端口
ServerSocket serverSocket = new ServerSocket(8801);
while (true){
try{
Socket socket = serverSocket.accept();
service(socket);
}catch (IOException e){
e.printStackTrace();
}
}
}
//模拟HTTP报文,输出hell,nio到浏览器
private static void service(Socket socket){
try{
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type:text/html;charset=utf-8");
String body = "hello,nio";
printWriter.println("Content-Length:" + body.getBytes().length);
printWriter.println();
printWriter.write(body);
printWriter.close();
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
服务器通信原理
业务场景:
NIO:
线程模型图
核心组件:
Selector:
Channe:
Buffer:
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
代码实例:
/**
* @Author qrn
* @Date 2021/5/5 下午9:43
* @Version 1.0
* @blog https://blog.csdn.net/qq_41971087
*/
public class BasicBuffer {
public static void main(String[] args) {
/**
* 创建一个buff 大小为5
*/
IntBuffer allocate = IntBuffer.allocate(5);
for(int i=0;i<allocate.capacity();i++){
allocate.put(i*2);
}
//读写转换
allocate.flip();
//循环打印buff的值
while (allocate.hasRemaining()){
System.out.println(allocate.get());
}
}
}
业务场景:
AIO:
描述
业务场景:
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/qq_41971087/article/details/116572886
粉丝福利:Java从入门到入土学习路线图
👇👇👇
👆长按上方微信二维码 2 秒
感谢点赞支持下哈
评论