1、socket 可以理解為傳輸層的一個編程規范


2、bio 以stream的方式

nio 以channel的方式


nio向本地文件中寫數據
@Test //往本地文件中寫數據
public void test1() throws Exception{
//1. 創建輸出流
FileOutputStream fos=new FileOutputStream("basic.txt");
//2. 從流中得到一個通道
FileChannel fc=fos.getChannel();
//3. 提供一個緩沖區
ByteBuffer buffer=ByteBuffer.allocate(1024);
//4. 往緩沖區中存入數據
String str="hello,nio";
buffer.put(str.getBytes());
//5. 翻轉緩沖區
buffer.flip();
//6. 把緩沖區寫到通道中
fc.write(buffer);
//7. 關閉
fos.close();
}
從本地文件讀取數據
@Test //從本地文件中讀取數據
public void test2() throws Exception{
File file=new File("basic.txt");
//1. 創建輸入流
FileInputStream fis=new FileInputStream(file);
//2. 得到一個通道
FileChannel fc=fis.getChannel();
//3. 準備一個緩沖區
ByteBuffer buffer=ByteBuffer.allocate((int)file.length());
//4. 從通道里讀取數據并存到緩沖區中
fc.read(buffer);
System.out.println(new String(buffer.array()));
//5. 關閉
fis.close();
}
nio網絡連接demo
java bio nio netty