ByteBuffer字符串缓冲区学习
capacity、limit、position、mark
Capacity 容量,即可以容纳的最大数据量;在缓冲区创建时被设定并且不能改变
Limit 表示缓冲区的当前终点,不能对缓冲区超过极限的位置进行读写操作。且极限是可以修改的
Position 位置,下一个要被读或写的元素的索引,每次读写缓冲区数据时都会改变改值,为下次读写作准备
Mark 标记,调用mark()来设置mark=position,再调用reset()可以让position恢复到标记的位置
BIO简单的模型
public static void main(String[] args) throws Exception{
ExecutorService threadPool = Executors.newCachedThreadPool();
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务器启动了");
while (true) {
System.out.println("主线程id:"+Thread.currentThread().getId()+"线程名称:"+Thread.currentThread().getName());
System.out.println("等待连接---->");
final Socket socket = serverSocket.accept();
System.out.println("连接上客户端");
threadPool.submit(() -> {
handler(socket);
});
}
}
public static void handler(Socket socket) {
try {
System.out.println("线程id:"+Thread.currentThread().getId()+"线程名称:"+Thread.currentThread().getName());
byte[] bytes = new byte[1024];
//获取输入流
InputStream inputStream = socket.getInputStream();
for (;;){
System.out.println("等待read----->");
int read = inputStream.read(bytes);
if (read != -1){
System.out.println("线程id:"+Thread.currentThread().getId()+"线程名称:"+Thread.currentThread().getName()+";获取数据为:---》"+new String(bytes,0,read));
}else {
break;
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}