java使用webSocket与前端通讯
1.Java_第一季_JAVASE_自增、单例模式、类与实例初始化过程、方法参数传递机制、递归和迭代、成员变量与局部变量2.Java_第一季_SSM_Spring Bean的作用域、Spring事务的传播行为、Spring MVC的执行流程、3.Java_第一季_java高级_Redis持久化、MySql何时建立索引4.java_JUC、volatile5.java_CAS6.java_阻塞队列(FIFO先进先出)7.JUC下countDownLatch、CyclicBarrier、Semaphore以及枚举的常见使用方法8.java_锁9.java_集合不安全10.Spring循环依赖11.AbstractQueuedSynchronizer---AQS12.LockSuport13.java_线程池7大参数_底层运行原理14.java_线程池三个常用方式15.Java_Callable<V>的基本使用16.java_锁_synchronized与Lock的区别17.java_强、软、弱、虚四大引用18.java_OOM19.JAVA-interview20.java_NIO21.java_JVM之GC22.java_JVM23.单例模式设计24.netty服务端、客户端简单搭建
25.java使用webSocket与前端通讯
26.java串口通讯27.用Java读取文件文字并语音播报28.Proguard-混淆29.Spring Security30.MQ31.spring相关面试题32.执行jar包33.Spring34.SpringBoot数据访问35.Java Stream(流)基本使用36.java集合工具类 Collections基本使用37.LocalDateTime、LocalDate、Date、String相互转化38.java8新特性39.java设计模式40.java springboot使用定时器41.MQ根据正常队列、死信队列来实现延迟队列的场景maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
WebSocket服务
import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Slf4j //映射webSocket服务路径 @ServerEndpoint("/webSocket/{userId}") @Component public class MyWebSocket { private String userId; private Session session; private static Map<String,MyWebSocket> client = new ConcurrentHashMap<>(); @OnOpen public void onOpen(@PathParam("userId") String userId,Session session){ log.info("新连接:{}",userId); if (!isEmpty(userId)){ this.userId = userId; this.session = session; client.put(userId, this); log.info("现在连接的客户编码为:" + userId); } } /** * 关闭时执行 */ @OnClose public void onClose() { log.info("连接:{} 关闭", this.userId); } /** * 收到消息时执行 * @param message * @param session */ @OnMessage public void onMessage(String message, Session session) { log.info("收到用户{}的消息:{}", this.userId, message); //回复用户 session.getAsyncRemote().sendText("收到 " + this.userId + " 的消息:" + message); } /** * 连接错误时执行 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.info("用户id为:{}的连接发送错误", this.userId); error.printStackTrace(); } /** * 消息点对点推送 * @param message */ public void sendMessageToUser(String userId,String message) { MyWebSocket session = client.get(userId); if (session != null) { if (session.session.isOpen()) { session.session.getAsyncRemote().sendText("收到 " + userId + " 的消息:" + message); } else { log.info("用户session关闭"); } } else { log.info("用户session不存在"); } } private static boolean isEmpty(String s) { return s == null || s.length() == 0 || "".equals(s) || "null".equalsIgnoreCase(s) || "undefined".equalsIgnoreCase(s); } }
webSocketConfig
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { /** * 启用Springboot对WebSocket的支持 * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
前端websocket(index.html)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> websocket Demo---- user000 <br /> <input id="text" type="text" /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"></div> <script type="text/javascript"> //判断当前浏览器是否支持WebSocket if('WebSocket' in window){ //ws://localhost:8080/webSocket/100,当前userId为100 websocket = new WebSocket("ws://localhost:8080/webSocket/100"); console.log("link success") }else{ alert('Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function(){ setMessageInnerHTML("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event){ setMessageInnerHTML("open"); } console.log("-----") //接收到消息的回调方法 websocket.onmessage = function(event){ setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function(){ setMessageInnerHTML("close"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function(){ websocket.close(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML){ document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭连接 function closeWebSocket(){ websocket.close(); } //发送消息 function send(){ var message = document.getElementById('text').value; websocket.send(message); } </script> </body> </html>
启动项目:访问
@GetMapping("/socket") public void socket(String userId,String message){ myWebSocket.sendMessageToUser(userId,message); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?