Java的BufferedWriter類主要用于文件操作,它提供了緩沖的寫入功能,可以提高寫入性能。雖然它本身并不是為網絡編程設計的,但你仍然可以在網絡編程中使用它。
在網絡編程中,你通常會使用Socket通信。以下是一個簡單的Java Socket服務器和客戶端示例,展示了如何使用BufferedWriter進行網絡通信:
服務器端:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
Socket socket = serverSocket.accept();
System.out.println("Client connected");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("Hello, client!");
writer.flush();
writer.close();
socket.close();
serverSocket.close();
}
}
客戶端:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = reader.readLine();
System.out.println("Server message: " + message);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("Hello, server!");
writer.flush();
writer.close();
socket.close();
}
}
在這個示例中,服務器和客戶端都使用了BufferedWriter來發送和接收數據。但請注意,這只是一個簡單的示例,實際的網絡編程可能需要處理更多的細節,例如異常處理、多線程等。