Java bio使用例子
时间: 2023-07-20 20:22:29 浏览: 106
下面是一个简单的Java BIO使用例子,实现了一个简单的通信服务端和客户端:
服务端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started, listening on port 8888...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client " + socket.getRemoteSocketAddress() + " connected");
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
try {
byte[] buffer = new byte[1024];
int n;
while ((n = is.read(buffer)) != -1) {
String s = new String(buffer, 0, n, "UTF-8");
System.out.println("Server received: " + s);
os.write(("Server received: " + s).getBytes("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Client " + socket.getRemoteSocketAddress() + " disconnected");
} finally {
socket.close();
}
}
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server " + socket.getRemoteSocketAddress());
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter message (type 'exit' to quit): ");
String line = scanner.nextLine();
if ("exit".equals(line)) {
break;
}
os.write(line.getBytes("UTF-8"));
byte[] buffer = new byte[1024];
int n = is.read(buffer);
String s = new String(buffer, 0, n, "UTF-8");
System.out.println("Client received: " + s);
}
socket.close();
}
}
```
这个例子实现了一个简单的回显服务器,客户端可以向服务器发送消息,服务器接收到消息后回复给客户端。
阅读全文