ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ package com.youge.nio.zerocopy; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020/11/27 11:37 */ import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; /** * NIO来传输读写文件 */ public class NewIOServer { public static void main(String[] args) throws IOException { //创建端口号 InetSocketAddress inetSocketAddress = new InetSocketAddress(7002); //创建serverSocketChannel对象 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //获取ServerSocket对象 ServerSocket serverSocket = serverSocketChannel.socket(); //绑定端口号 serverSocket.bind(inetSocketAddress); //创建buffer ByteBuffer buffer = ByteBuffer.allocate(4096); while (true) { //获取客户端连接过来的socketChannel SocketChannel socketChannel = serverSocketChannel.accept(); int readCount = 0; while (-1 != readCount) { readCount = socketChannel.read(buffer); System.out.println(readCount); buffer.rewind();//倒带 position =0,mark作废 } } } } ~~~