在Java中實(shí)現(xiàn)網(wǎng)絡(luò)通信,通常需要使用到Java套接字編程(Socket Programming)。套接字是一種用于實(shí)現(xiàn)不同計(jì)算機(jī)間或同一計(jì)算機(jī)內(nèi)的進(jìn)程間通信的技術(shù)。以下是一個(gè)簡(jiǎn)單的Java網(wǎng)絡(luò)通信示例,展示了如何使用TCP協(xié)議進(jìn)行客戶端和服務(wù)器之間的通信:
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();
}
}
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();
}
}
首先運(yùn)行服務(wù)器端代碼(Server.java),然后運(yùn)行客戶端代碼(Client.java)??蛻舳藢⑦B接到服務(wù)器并發(fā)送消息,服務(wù)器將接收消息并將其原樣返回。當(dāng)客戶端輸入"exit"時(shí),連接將關(guān)閉。