Home >Java >javaTutorial >How to configure and use sockets in Java network programming?
Socket is the foundation of network programming, allowing applications to communicate with each other over the network. This guide provides detailed steps on how to configure and use Socket: Create a Socket: Specify the port and address. Using sockets: the server listens for connections, reads and writes data; the client connects to the server, sends and receives data. Practical case: Build a simple chat application to demonstrate how to use Socket for two-way communication.
Java Network Programming: Socket Configuration and Usage Guide
Socket (Socket) is the basis of network programming and allows applications Programs communicate with each other over a network. This guide explains how to configure and use sockets in Java.
Configuring the socket
The steps to create a socket are as follows:
// 创建一个 ServerSocket 监听端口 8080 ServerSocket serverSocket = new ServerSocket(8080); // 创建一个 Socket 客户端连接到 localhost:8080 Socket clientSocket = new Socket("localhost", 8080);
Using the socket
Server side:
// 接受客户端连接 Socket clientSocket = serverSocket.accept(); // 获取输入流和输出流 DataInputStream input = new DataInputStream(clientSocket.getInputStream()); DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream()); // 读写数据 String message = input.readUTF(); output.writeUTF("Hello from server: " + message); // 关闭连接 clientSocket.close();
Client side:
// 发送数据到服务器 DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream()); output.writeUTF("Hello from client"); // 接收服务器响应 DataInputStream input = new DataInputStream(clientSocket.getInputStream()); String serverMessage = input.readUTF(); // 关闭连接 clientSocket.close();
Actual case
Build a simple chat application:
Server code:
ServerSocket serverSocket = new ServerSocket(8080); Socket clientSocket = serverSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true); while (true) { String message = input.readLine(); if (message == null || message.isEmpty()) { break; } output.println("Server: " + message); }
Client code:
Socket clientSocket = new Socket("localhost", 8080); BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true); output.println("Hello from client"); String serverMessage = input.readLine(); System.out.println(serverMessage);
The above is the detailed content of How to configure and use sockets in Java network programming?. For more information, please follow other related articles on the PHP Chinese website!