三种IO模型
BIO简单代码实现
服务器端
public class SocketBioServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9001);
while (true) {
System.out.println("服务器端正在等待连接中...");
// 阻塞方法 如果没有客户端与服务器端建立连接时,该方法会阻塞等待
final Socket socket = serverSocket.accept();
System.out.println("有客户端和我连接啦");
//如果不使用异步线程处理接受io操作的情况下,有可能会阻塞等待 无法接受新的连接请求。
new Thread(() -> {
try {
handler(socket);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
// handler(socket);
}
}
private static void handler(Socket socket) throws IOException {
System.out.println("线程id= " + Thread.currentThread().getId());
byte[] bytes = new byte[1024];
System.out.println("开始read。。");
//接收客户端的数据,如果没有读取到客户端数据时,该方法也会阻塞
int read = socket.getInputStream().read(bytes);
System.out.println("read结束");
if (read != -1) {
System.out.println("接收到客户端的数据:" + new String(bytes, 0, read));
System.out.println("线程id= = " + Thread.currentThread().getId());
}
socket.getOutputStream().write("效果演示完毕~~".getBytes());
socket.getOutputStream().flush();
}
}
客户端
public class SocketBioClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 9001);
//向服务端发送数据
socket.getOutputStream().write("来演示下同步阻塞Bio".getBytes());
socket.getOutputStream().flush();
System.out.println("向服务端发送数据结束");
byte[] bytes = new byte[1024];
//接收服务端回传的数据
socket.getInputStream().read(bytes);
System.out.println("接收到服务端的数据:" + new String(bytes));
socket.close();
}
}
NIO简单代码实现
服务器端
public class SimulationNioTcpServer {
/**
* 保存SocketChannel
*/
private static List<SocketChannel> listSocketChannel = new ArrayList<>();
/**
* 缓冲区大小
*/
private static ByteBuffer byteBuffer = ByteBuffer.allocate(512);
public static void main(String[] args) {
try {
// 1.创建一个ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 2. 绑定地址
ServerSocketChannel bind = serverSocketChannel.bind(new InetSocketAddress(8080));
// 3.设置非阻塞模式
serverSocketChannel.configureBlocking(false);
while (true) {
// 4.等待建立连接 如果设置非阻塞的情况下,如果没有获取连接的情况下直接返回null,如果建立连接之后返回socketChannel
// 建立三次握手
SocketChannel socketChannel = serverSocketChannel.accept();
// 5. 如果socketChannel 不为空的情况下,则将该连接保存起来。
if (socketChannel != null) {
// 设置该socketChannel通道为fasle
socketChannel.configureBlocking(false);
listSocketChannel.add(socketChannel);
}
// 循环SocketChannel,检查每个SocketChannel中数据有传输数据
for (SocketChannel scl : listSocketChannel) {
try {
// 6.以缓冲区方式读取
int read = scl.read(byteBuffer);
if (read > 0) {
byteBuffer.flip();
// 转换格式为中文的格式
Charset charset = Charset.forName("UTF-8");
String receiveText = charset.newDecoder().decode
(byteBuffer.asReadOnlyBuffer()).toString();
System.out.println("receiveText:" + receiveText);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
-------资源转载于蚂蚁课堂(www.mayikt.com)