Java中 BIO的代码示例和使用场景
时间: 2024-10-29 16:15:26 浏览: 25
BIO全称是Blocking I/O,即阻塞I/O,在Java中主要体现在`java.io`包下的`InputStream`、`OutputStream`等流处理上。当从网络或其他源读取数据时,如果数据不可立即获取,BIO会一直阻塞等待,直到数据可用。
下面是一个简单的BIO网络通信的代码示例,使用`Socket`和`PrintWriter`进行服务器端和客户端的连接:
**服务器端(Server.java)**:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8000);
Socket client = null;
while ((client = server.accept()) != null) {
Thread thread = new Thread(new ClientHandler(client));
thread.start();
}
}
}
class ClientHandler implements Runnable {
private final Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {
String requestLine;
while ((requestLine = reader.readLine()) != null) {
System.out.println("Received: " + requestLine);
writer.println("Hello from Server!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
**客户端(Client.java)**:
```java
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
String host = "localhost";
int port = 8000;
Socket socket = new Socket(InetAddress.getByName(host), port);
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
writer.write("GET / HTTP/1.1\n");
writer.newLine();
writer.write("Host: " + host + "\n");
writer.newLine();
writer.write("Connection: close\n");
writer.newLine();
System.out.println("Sent request to " + host + ":" + port);
String responseLine;
while ((responseLine = reader.readLine()) != null) {
System.out.println("Received: " + responseLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
BIO的主要应用场景是在并发不是特别高的场景下,因为其同步阻塞的特性,不适合大量并发连接的高性能网络服务,比如Web服务器。在现代应用中,非阻塞I/O(NIO)和反应式编程更受欢迎,它们提供了解决高并发的能力。
阅读全文