如何实现Java Socket的双向通信

avatar
作者
筋斗云
阅读量:0

要实现Java Socket的双向通信,你需要创建一个服务器端和客户端,它们可以通过套接字(Socket)进行数据的发送和接收。以下是一个简单的示例,展示了如何实现双向通信。

首先,我们创建一个服务器端:

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 running on port: " + port);          Socket socket = serverSocket.accept();         System.out.println("Client connected");          InputStream input = socket.getInputStream();         OutputStream output = socket.getOutputStream();          BufferedReader reader = new BufferedReader(new InputStreamReader(input));         PrintWriter writer = new PrintWriter(output, true);          String line;         while (true) {             line = reader.readLine();             if (line != null) {                 System.out.println("Received from client: " + line);                 writer.println("Server received: " + line);             }         }     } } 

接下来,我们创建一个客户端:

import java.io.*; import java.net.*;  public class Client {     public static void main(String[] args) throws IOException {         String host = "localhost";         int port = 12345;          Socket socket = new Socket(host, port);         System.out.println("Connected to server");          InputStream input = socket.getInputStream();         OutputStream output = socket.getOutputStream();          BufferedReader reader = new BufferedReader(new InputStreamReader(input));         PrintWriter writer = new PrintWriter(output, true);          BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));          String line;         while (true) {             System.out.print("Enter message: ");             line = userInput.readLine();             writer.println(line);              line = reader.readLine();             if (line != null) {                 System.out.println("Server response: " + line);             }         }     } } 

在这个示例中,服务器端和客户端都使用了Socket对象来创建连接。服务器端使用ServerSocket对象监听指定端口,等待客户端连接。当客户端连接后,服务器端和客户端可以通过InputStreamOutputStream进行数据的读取和写入,从而实现双向通信。

要运行此示例,请先运行服务器端,然后运行客户端。你将看到它们之间的双向通信。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!