BIO:Block Input Output 阻塞式的输入和输出,面向数据流。示例代码如下:
1、服务端Server
package com.example.bio.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class BioServer {
public static void main(String[] args) {
//BIO代码
try {
ServerSocket server = new ServerSocket(8080);
System.out.println("BIO服务端启动......");
//此处可以做成线程池,支持多客户端连接,为了简单示例中不再体现
Socket socket = server.accept();
if(socket.isConnected()){
System.out.println("BIO客户端已连接......");
}
PrintWriter pw = new PrintWriter(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = br.readLine();
System.out.println("服务端接收到客户端信息为:"+ message);
pw.println("Client Say \" hello Bio\"");
pw.close();
br.close();
socket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、客户端Client
package com.example.bio.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class BioClient {
public static void main(String[] args) {
//BIO
try {
Socket socket = new Socket("127.0.0.1",8080);
if(socket.isConnected()){
System.out.println("客户端已连接到服务器......");
}
PrintWriter pw = new PrintWriter(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String name = "hello Bio";
pw.println(name);
pw.flush();
System.out.println("客户端接收到服务端信息为:" + br.readLine());
pw.close();
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后给个运行结果截图: