欢迎访问我的个人博客:L_SKH’Blog
概述:
BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,但程序简单易理解。
Java BIO 就是传统的java io 编程,其相关的类和接口在 java.io BIO(blocking I/O) : 同步阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,可以通过线程池机制改善(实现多个客户连接服务器)。
BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,程序简单易理解。
代码实现
因为是bio,所以我们线程池采用CachedThreadPool,不了解线程池的可以去看一下我之前的一篇博客。
package org.skh.bio;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Created IntelliJ IDEA.
* @Author L_SKH
* @Date 2019/11/21 18:41
*/
public class BIOServer {
public static void main(String[] args) throws IOException {
//创建线程池 来一个任务就产生一个线程 所以使用CachedPool
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("Service Start.....");
while (true) {
//监听端口
final Socket socket = serverSocket.accept();//也会阻塞
System.out.println("一个客户端连接...");
newCachedThreadPool.execute(()->{
byte[] bytes = new byte[1024];
try {
InputStream inputStream = socket.getInputStream();
//循环的读取客户端发送的数据
while (true){
int read = inputStream.read(bytes);
if (read!=-1){
System.out.println(read);
System.out.println("线程"+Thread.currentThread().getName()+"收到的信息:"+new String(bytes,0,read));
}else{
break ;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
System.out.println("Close Connection...");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}
测试结果
在这里我们通过telnet连接两个客户端来查看结果:
telnet 127.0.0.1 6666