IO
这里先讲一下io
众所周知io是阻塞式的 但是在很多博客中并没有实例解释
io又称为bio 是面向流的 阻塞式io 让我们用代码来展示一下
这里我们开通一个服务端 端口为8089 这里使用while true 使服务端始终处于监听状态
public class bioservice {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8089);
while(true){
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] bs = new byte[1024];
int len = inputStream.read(bs);
if (len>0){
System.out.println(new String(bs,0,len));
}}
} catch (IOException e) {
e.printStackTrace();
}
}
}
新建两个客户端
public class bioclientone {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost",8089);
OutputStream outputStream = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
outputStream.write(br.readLine().getBytes());
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class bioclientone1 {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost",8089);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("哈哈哈1111".getBytes());
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
依次运行服务端 客户端 客户端1
此时的服务端输出为
而客户端1已经结束了
证明客户端1发送的消息被阻塞
这是从bioclientone 发送消息
这是我们会发现服务端一次接受了两个消息
以此来证明了bio 是阻塞时io