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

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.lryc.cn/news/2404352.html

相关文章:

  • STM32学习之I2C(理论篇)
  • 【C/C++】algorithm清单以及适用场景
  • Python_day47
  • 如何在mac上安装podman
  • 小黑一层层削苹果皮式大模型应用探索:langchain中智能体思考和执行工具的demo
  • CppCon 2015 学习:Intro to the C++ Object Model
  • Go 语言中的 make 函数详解
  • 阿里云ACP云计算备考笔记 (4)——企业应用服务
  • 用 NGINX 构建高效 SMTP 代理`ngx_mail_smtp_module`
  • 【前端】常用组件的CSS
  • 【华为云学习与认证】以华为云物联网为基座的全栈开发(从物联网iot平台模块到应用展示、数据分析、机器学习、嵌入式开发等)的系统性学习与认证路线
  • OpenCV 键盘响应来切换图像
  • ARM SMMUv3简介(一)
  • C#提取CAN ASC文件时间戳:实现与性能优化
  • hadoop集群datanode启动显示init failed,不能解析hostname
  • Android 视图系统入门指南
  • 浏览器工作原理05 [#] 渲染流程(上):HTML、CSS和JavaScript是如何变成页面的
  • 青少年编程与数学 01-011 系统软件简介 03 NetWare操作系统
  • AI编程提示词
  • Android学习总结-GetX库常见问题和解决方案
  • |从零开始的Pyside2界面编程| 用Pyside2打造一个AI助手界面
  • React 中 HTML 插入的全场景实践与安全指南
  • 一键更新依赖全指南:Flutter、Node.js、Kotlin、Java、Go、Python 等主流语言全覆盖
  • Java异步编程难题拆解技术
  • NoSQL 之 Redis 配置与优化
  • pikachu靶场通关笔记20 SQL注入03-搜索型注入(GET)
  • 产品笔试专业名词梳理
  • 【前端】es6相关,柯里化
  • 51单片机基础部分——矩阵按键检测
  • onSaveInstanceState() 和 ViewModel 在数据保存能力差异