before java网络通信如何实现

avatar
作者
猴君
阅读量:0

在Java中实现网络通信,通常需要使用到Java套接字编程(Socket Programming)。套接字是一种用于实现不同计算机间或同一计算机内的进程间通信的技术。以下是一个简单的Java网络通信示例,展示了如何使用TCP协议进行客户端和服务器之间的通信:

  1. 服务器端代码(Server.java):
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");          InputStream inputStream = socket.getInputStream();         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));          OutputStream outputStream = socket.getOutputStream();         PrintWriter writer = new PrintWriter(outputStream, true);          String line;         while ((line = reader.readLine()) != null) {             System.out.println("Received: " + line);             writer.println("Server received: " + line);         }          socket.close();         serverSocket.close();     } } 
  1. 客户端代码(Client.java):
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");          OutputStream outputStream = socket.getOutputStream();         PrintWriter writer = new PrintWriter(outputStream, true);          InputStream inputStream = socket.getInputStream();         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));          BufferedReader console = new BufferedReader(new InputStreamReader(System.in));         String line;          while (true) {             System.out.print("Enter a message: ");             line = console.readLine();             if (line == null || line.equalsIgnoreCase("exit")) {                 break;             }              writer.println(line);             System.out.println("Sent: " + line);              String response = reader.readLine();             System.out.println("Server response: " + response);         }          socket.close();     } } 

首先运行服务器端代码(Server.java),然后运行客户端代码(Client.java)。客户端将连接到服务器并发送消息,服务器将接收消息并将其原样返回。当客户端输入"exit"时,连接将关闭。

广告一刻

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