Java I/O streams are used in conjunction with network communication to provide a standard mechanism for handling network data interaction. Achieve this through the following steps: Establish a Socket connection. Get the Socket input/output stream. Read Socket data using an input stream. Use an output stream to write Socket data.
Combined use of Java I/O streams and network communication
Understanding I/O streams
I/O (input/output) streams are an abstraction in Java for reading and writing data from a device or network. They provide standard portable mechanisms for handling different data sources.
Understanding network communication
Java provides a robust API for network communication, including creating sockets, sending and receiving data. The Socket class is the core of network communication and represents a connection to a remote computer.
Combined use of I/O streams and network communication
I/O streams and network communications can be integrated together to achieve data interaction through the network. The following are the specific steps:
Practical Case
The following is a client-server chat application implemented in Java that demonstrates the combined use of I/O streams and network communication. :
Client:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Client { public static void main(String[] args) { String hostname = "localhost"; int port = 5000; try (Socket socket = new Socket(hostname, port); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream())) { // 发送消息到服务器 out.println("Hello from client!"); // 读取服务器响应 String serverResponse = in.readLine(); System.out.println("Received from server: " + serverResponse); } catch (IOException e) { e.printStackTrace(); } } }
Server:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { int port = 5000; try (ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream())) { // 读取客户端消息 String clientMessage = in.readLine(); System.out.println("Received from client: " + clientMessage); // 发送响应到客户端 out.println("Hello from server!"); } catch (IOException e) { e.printStackTrace(); } } }
Run
java Server
java Client
The above is the detailed content of How are Java I/O streams used together with network communication?. For more information, please follow other related articles on the PHP Chinese website!