SpringBoot实现WebSocket
温馨提示:
本文最后更新于 2022年10月19日,已超过 555 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
创建springboot项目,在pox.xml中加入(下面是我的pom.xml的dependencies里的全部依赖,因为,这个是最简单的入门例子,所以只有主要的websocket和web依赖)
引入依赖
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-starter-test
test
WebSockTest编写
/**
* @ServerEndPoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL连接到websocket服务器端
*/
@ServerEndpoint("/websocket")
@Component
public class WebSockTest {
private static int onlineCount=0;
private static CopyOnWriteArrayList webSocketSet=new CopyOnWriteArrayList();
private Session session;
@OnOpen
public void onOpen(Session session){
this.session=session;
webSocketSet.add(this);//加入set中
addOnlineCount();
System.out.println("有新连接加入!当前在线人数为"+getOnlineCount());
}
@OnClose
public void onClose(){
webSocketSet.remove(this);
subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message,Session session){
System.out.println("来自客户端的消息:"+message);
// 群发消息
for (WebSockTest item:webSocketSet){
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
@OnError
public void onError(Session session,Throwable throwable){
System.out.println("发生错误!");
throwable.printStackTrace();
}
// 下面是自定义的一些方法
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount(){
return onlineCount;
}
public static synchronized void addOnlineCount(){
WebSockTest.onlineCount++;
}
public static synchronized void subOnlineCount(){
WebSockTest.onlineCount--;
}
}
SpringBoot要注入ServerEndpointExporter
注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。 要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter, 因为它将由容器自己提供和管理。
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
前端编码测试
创建一个页面index.html,前端跳转后端的一些必要代码
Java后端WebSocket的Tomcat实现
Welcome
启动项目后,可以同时访问几个页面,发送实时消息。
访问链接:http://localhost:8080
正文到此结束
- 本文标签: 后端 Spring Boot WebSocket
- 本文链接: http://www.92cxy.cn/article/49
- 版权声明: 本文由王小东原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
热门推荐
相关文章
该篇文章的评论功能已被站长关闭