一、BIO
BIO,即同步并阻塞。服务端会在ServerSocket对象的accept方法发生阻塞,当有连接进入的时候,才能继续往下执行;读取数据,调用read方法时,也会发生阻塞。
二、服务端
public class BIOServer {
public static void main(String[] args) {
try {
openServer(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void openServer(int port) throws IOException {
// 创建ServerSocket
ServerSocket serverSocket = new ServerSocket();
// 绑定端口
serverSocket.bind(new InetSocketAddress(port));
System.out.println("BIOServer启动...");
while (true){
// 堵塞,等待客户端连接
Socket socket = serverSocket.accept();
System.out.println("连接成功...");
// 输入流
// BufferedReader是缓冲输入流,InputStreamReader是转换输入流,InputStream是字节输入流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = null;
while ((str = br.readLine()) != null){
if("quit".equals(str)){
break;
}
System.out.println(str);
}
// 关闭流
br.close();
// 关闭socket
socket.close();
System.out.println("连接结束...");
}
// System.out.println("BIOServer关闭...");
}
}
三、客户端
public class BIOClient {
public static void main(String[] args) {
try {
connect("127.0.0.1", 8888);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void connect(String hostname, int port) throws IOException {
// 创建socket
Socket socket = new Socket();
// 连接
socket.connect(new InetSocketAddress(hostname, port));
// 输出流
// BufferedWriter是缓冲输出流,OutputStreamWriter是转换输出流,OutputStream是字节输出流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// 标准输入流,从键盘输入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while ((str = br.readLine()) != null){
// 如果从键盘输入quit,则退出循环
if ("quit".equals(str)){
break;
}
bw.write(str);
// 需要写换行,因为server端每次读取一行
bw.newLine();
bw.flush();
}
// 关闭流
br.close();
// 关闭socket
socket.close();
}
}