BIO的简单实例

时间:2020-05-09
本文章向大家介绍BIO的简单实例,主要包括BIO的简单实例使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

BIO是一种同步阻塞的连接方式 一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销

关于BIO 有如下的简单实现:

public class BioServer {
public static void main(String[] args) throws IOException {
//创建一个线程池
//如果有客户端与之连接 就创建一个线程与之通讯
ExecutorService executorService= Executors.newCachedThreadPool();
//创建ServerSocket
ServerSocket serverSocket=new ServerSocket(6666);
System.out.println("服务器启动了");
while(true){
System.out.println("等待连接");
//监听 等待客户端连接
final Socket socket=serverSocket.accept();
System.out.println("连接到一个客户端");
//创建一个线程与之通讯
executorService.execute(new Runnable() {
@Override
public void run() {
handler(socket);
}
});

}
}
//编写一个方法 和客户端通信
public static void handler(Socket socket) {
//接收数据
byte[] bytes=new byte[1024];
//通过socket获取输入流
try {
System.out.println("id"+Thread.currentThread().getId()+"名字"+Thread.currentThread().getName());
System.out.println("read...");
InputStream inputStream = socket.getInputStream();
while (true){
System.out.println("id"+Thread.currentThread().getId()+"名字"+Thread.currentThread().getName());
int read =inputStream.read(bytes);
//输出传输的数据
if(read!=-1){
System.out.println(new String(bytes,0,read));
}
else
{
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
System.out.println("关闭和client的连接");
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

    }

启动时 会出现:

说明 阻塞在了这里:while(true){
            System.out.println("等待连接");

当连接到客户端时:

 连接到客户端后 阻塞的线程开始运行  运行到

         try {

    System.out.println("id"+Thread.currentThread().getId()+"名字"+Thread.currentThread().getName());
System.out.println("read...");
又被阻塞
所以 BIO同步并阻塞 如果连接不做任何事情会造成不必要的线程开销

原文地址:https://www.cnblogs.com/mc-74120/p/12855272.html