Java客戶端與服務器通信
Java提供了多種方式來實現客戶端與服務器之間的通信,下面我將介紹幾種常見的方法:
1. 基于Socket的基本通信
服務器端代碼
import java.io.*; import java.net.*;public class SimpleServer {public static void main(String[] args) {try {ServerSocket serverSocket = new ServerSocket(8080);System.out.println("服務器啟動,等待客戶端連接...");Socket clientSocket = serverSocket.accept();System.out.println("客戶端已連接: " + clientSocket.getInetAddress());// 獲取輸入輸出流BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);// 通信循環String inputLine;while ((inputLine = in.readLine()) != null) {System.out.println("收到客戶端消息: " + inputLine);out.println("服務器回復: " + inputLine);}// 關閉連接in.close();out.close();clientSocket.close();serverSocket.close();} catch (IOException e) {e.printStackTrace();}} }
客戶端代碼
import java.io.*; import java.net.*;public class SimpleClient {public static void main(String[] args) {try {Socket socket = new Socket("localhost", 8080);// 獲取輸入輸出流PrintWriter out = new PrintWriter(socket.getOutputStream(), true);BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));// 發送消息out.println("Hello, Server!");// 接收回復String response = in.readLine();System.out.println("服務器回復: " + response);// 關閉連接out.close();in.close();socket.close();} catch (IOException e) {e.printStackTrace();}} }
2. 使用Java RMI (遠程方法調用)
RMI允許一個Java程序調用另一個Java虛擬機上對象的方法。
定義遠程接口
import java.rmi.Remote; import java.rmi.RemoteException;public interface RemoteService extends Remote {String sayHello(String name) throws RemoteException; }
實現遠程服務
import java.rmi.*; import java.rmi.server.*;public class RemoteServiceImpl extends UnicastRemoteObject implements RemoteService {public RemoteServiceImpl() throws RemoteException {super();}public String sayHello(String name) throws RemoteException {return "Hello, " + name + "!";} }
服務器端代碼
import java.rmi.registry.*;public class RMIServer {public static void main(String[] args) {try {RemoteService service = new RemoteServiceImpl();LocateRegistry.createRegistry(1099);Naming.rebind("RemoteService", service);System.out.println("RMI服務已啟動...");} catch (Exception e) {e.printStackTrace();}} }
客戶端代碼
import java.rmi.*;public class RMIClient {public static void main(String[] args) {try {RemoteService service = (RemoteService) Naming.lookup("rmi://localhost/RemoteService");String response = service.sayHello("Client");System.out.println("服務器回復: " + response);} catch (Exception e) {e.printStackTrace();}} }
3. 使用HTTP通信 (HttpURLConnection)
客戶端HTTP請求示例
import java.io.*; import java.net.*;public class HttpClientExample {public static void main(String[] args) {try {URL url = new URL("http://example.com/api");HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 設置請求方法connection.setRequestMethod("GET");// 獲取響應int responseCode = connection.getResponseCode();System.out.println("響應代碼: " + responseCode);BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String inputLine;StringBuilder response = new StringBuilder();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();System.out.println("響應內容: " + response.toString());} catch (Exception e) {e.printStackTrace();}} }
4. 使用第三方庫 - Apache HttpClient
import org.apache.http.client.methods.*; import org.apache.http.impl.client.*; import org.apache.http.util.EntityUtils;public class ApacheHttpClientExample {public static void main(String[] args) {try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpGet request = new HttpGet("http://example.com/api");try (CloseableHttpResponse response = httpClient.execute(request)) {System.out.println("狀態碼: " + response.getStatusLine().getStatusCode());String result = EntityUtils.toString(response.getEntity());System.out.println("響應內容: " + result);}} catch (Exception e) {e.printStackTrace();}} }
5. WebSocket通信
服務器端 (使用Java EE或Spring)
import javax.websocket.*; import javax.websocket.server.*;@ServerEndpoint("/websocket") public class WebSocketServer {@OnOpenpublic void onOpen(Session session) {System.out.println("客戶端連接: " + session.getId());}@OnMessagepublic void onMessage(String message, Session session) {System.out.println("收到消息: " + message);try {session.getBasicRemote().sendText("服務器回復: " + message);} catch (IOException e) {e.printStackTrace();}}@OnClosepublic void onClose(Session session) {System.out.println("客戶端斷開: " + session.getId());} }
客戶端 (使用Java API)
import javax.websocket.*;@ClientEndpoint public class WebSocketClient {@OnOpenpublic void onOpen(Session session) {System.out.println("連接已建立");try {session.getBasicRemote().sendText("Hello, Server!");} catch (IOException e) {e.printStackTrace();}}@OnMessagepublic void onMessage(String message) {System.out.println("收到服務器消息: " + message);}public static void main(String[] args) {WebSocketContainer container = ContainerProvider.getWebSocketContainer();try {container.connectToServer(WebSocketClient.class, URI.create("ws://localhost:8080/websocket"));Thread.sleep(5000); // 保持連接一段時間} catch (Exception e) {e.printStackTrace();}} }
選擇建議
-
簡單通信:使用Socket或HttpURLConnection
-
分布式應用:考慮RMI或RPC框架
-
Web服務:使用HTTP客戶端庫
-
實時雙向通信:WebSocket是更好的選擇