Springboot基于websocket实现简单在线聊天功能

网友投稿 351 2022-12-03


Springboot基于websocket实现简单在线聊天功能

添加maven依赖

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

org.springframework.boot

spring-boot-starter-parent

2.2.5.RELEASE

4.0.0

springboot-websocket

springboot-websocket

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-websocket

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

org.springframework.boot

spring-boot-starter-parent

2.2.5.RELEASE

4.0.0

springboot-websocket

springboot-websocket

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-websocket

添加websocket配置

@Configuration

@EnableWebSocket

public class MyWebSocketConfig implements WebSocketConfigurer {

@Override

public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

registry.addHandler(myHandler(), "/myHandler").setAllowedOrigins("*");

}

@Bean

public WebSocketHandler myHandler() {

return new MyTextWebSocketHandler();

}

}

实现具体的handler

public class MyTextWebSocketHandler extends TextWebSocketHandler {

private Set sessions = new HashSet<>();http://

@Override

protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

if (session.isOpen()) {

sessions.add(session);

}

sendToAll(message);

}

private void sendToAll(TextMessage message) throws IOException {

for (WebSocketSession session : sessions) {

session.sendMessage(message);

}

}

@Override

public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

sessions.remove(session);

}

}

即可通过ws://localhost:8080/myHandler访问websocket

添加测试页面:

当前用户:

发送消息:


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java操作Redis缓存设置过期时间的方法
下一篇:详细分析java并发之volatile关键字
相关文章

 发表评论

暂时没有评论,来抢沙发吧~