BIO简介
BIO是阻塞的I/O,所有的文件操作都是阻塞的。程序在调用读写操作的时候,在数据返回前会一直等待,直到数据包被复制到应用进程的缓冲区或者发生异常的时候才返回。
下面以Socket编程演示java BIO
Socket
服务端开启监听,处理客户端发来的请求。
public static void main(String[] args) {
//创建ServerSocket并绑定端口
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10100);
//监听连接,方法会阻塞直到建立连接
while (true) {
Socket socket = serverSocket.accept();
BIOServerHandle handle = new BIOServerHandle(socket);
Thread thread = new Thread(handle);
thread.start();
}
} catch (IOException e) {
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BIOServerHandler处理请求
public class BIOServerHandle implements Runnable {
private Socket socket;
public BIOServerHandle(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
//读取客户端的数据
inputStream = socket.getInputStream();
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
String msg = new String(buffer, "UTF-8");
System.out.println("服务器接收到客户端的消息:" + msg);
} catch (Exception e) {
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
客户端发起请求
public static void main(String[] args) {
Socket socket = null;
OutputStream outputStream = null;
InputStream inputStream = null;
try {
//建立连接
socket = new Socket("127.0.0.1", 10100);
outputStream = socket.getOutputStream();
String msg = "hello--------------";
System.out.println("向服务器发送消息:"+msg);
//向服务器发送数据
outputStream.write(msg.getBytes());
} catch (IOException e) {
//
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
演示结果