轻量级前端框架助力开发者提升项目效率与性能
654
2023-05-22
Springboot基于websocket实现简单在线聊天功能
添加maven依赖
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
添加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
@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
添加测试页面:
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:8080/myHandler");
ws.onopen = function () {
};
ws.onmessage = function (evt) {
document.getElementById('messageDiv').innerHTML += evt.data + "";
};
ws.onclose = function () {
console.log("close connect");
};
} else {
alert("您的浏览器不支持 WebSocket!");
}
function send() {
ws.send(document.getElementById("input").value + ": " + document.getElementById("message").value);
}
当前用户:
发送消息:
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~