您现在的位置是:首页 > 后台技术 > JavaJava
java实现websocket(图文)
第十三双眼睛2021-02-13【Java】人已围观
简介WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
1首先添加依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
这里没有版本号,是因为我的项目是springboot项目,版本继承父项目的。否则需要写版本号
2添加如下的类
3写一个类,在头部写
@Component
@ServerEndpoint("/websocket")
实现如下方法:
onOpen、onClose、onMessage、onError方法即可。非常简单吧。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
这里没有版本号,是因为我的项目是springboot项目,版本继承父项目的。否则需要写版本号
2添加如下的类
package com.xinchen.fan.websocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { private Logger infoLogger = LoggerFactory.getLogger("info"); /** * 检测所有带有@serverEndpoint注解的bean并注册他们。 * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { System.out.println("我被注入了"); infoLogger.info("我被注入了"); return new ServerEndpointExporter(); } } |
@Component
@ServerEndpoint("/websocket")
实现如下方法:
onOpen、onClose、onMessage、onError方法即可。非常简单吧。
很赞哦! ()
上一篇:shiro学习(图文)