当前位置: 首页 > backend >正文

Java应用10(客户端与服务器通信)

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();}}
}

选择建议

  1. 简单通信:使用Socket或HttpURLConnection

  2. 分布式应用:考虑RMI或RPC框架

  3. Web服务:使用HTTP客户端库

  4. 实时双向通信:WebSocket是更好的选择

http://www.xdnf.cn/news/12317.html

相关文章:

  • App使用webview套壳引入h5(一)—— webview和打开的h5进行通信传参
  • 为什么 SDXL 用两个文本编码器?
  • aiohttp异步爬虫实战:从零构建高性能图书数据采集系统(2025最新版)
  • 华为交换机vlan配置步骤
  • 【git】把本地更改提交远程新分支feature_g
  • Python 网络编程 -- WebSocket编程
  • Java线程安全集合类
  • NumPy 比较、掩码与布尔逻辑
  • [AI绘画]sd学习记录(一)软件安装以及文生图界面初识、提示词写法
  • rapidocr 3.0 在线demo来了
  • 时序预测模型测试总结
  • Langchain4j RAG和向量搜索(8)
  • Linux网桥实战手册:从基础配置到虚拟化网络深度优化
  • AdvancedLivePortrait V2版 - 一张照片生成生动任意表情图片/视频,支持50系显卡 本地一键整合包下载
  • Java多线程编程全面解析:从基础概念到实战应用
  • Abaqus的线弹性与塑性
  • 监测预警系统重塑隧道安全新范式
  • CSP-VP37th
  • 使用 OpenAI Moderation 实现内容审核
  • 看板中“进行中”任务过多如何优化
  • 深度学习题目1
  • CppCon 2015 学习:C++ Metaprogrammin
  • ECB(电子密码本,Electronic Codebook) 和 CBC(密码分组链接,Cipher Block Chaining)区分于用途
  • 合并表格(按行合并)
  • 黑马Java面试笔记之 并发编程篇(线程池+使用场景)
  • 软件项目管理(1) 项目管理概述
  • Excel数据分析:基础
  • Java-IO流之缓冲流详解
  • 【Maniskill】使用Ppo的官方基线训练时出现指标突然“塌陷”的现象
  • STM32入门教程——OLED调试工具