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来发送和接收数据。但请注意,这只是一个简单的示例,实际的网络编程可能需要处理更多的细节,例如异常处理、多线程等。