Springboot websocket学习Demo
2021-02-19 03:18
标签:line throwable bool ++ framework end move eve lse 使用的是springboot2.1.4版本 引入依赖 要使用websocket需要一个Bean,否则报错Error during WebSocket handshake:之类的问题 后端代码WebSocketServer.java 前端代码index.html 后面是我的总结,如果有什么地方不对的,请留言: Springboot websocket学习Demo 标签:line throwable bool ++ framework end move eve lse 原文地址:https://www.cnblogs.com/TheoryDance/p/12686480.html parent>
groupId>org.springframework.bootgroupId>
artifactId>spring-boot-starter-parentartifactId>
version>2.1.4.RELEASEversion>
relativePath />
parent>
dependency>
groupId>org.springframework.bootgroupId>
artifactId>spring-boot-starter-websocketartifactId>
dependency>
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@ServerEndpoint("/imserver/{userId}")
@Component
@Slf4j
public class WebSocketServer {
/**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
private static int onlineCount = 0;
/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
private static ConcurrentHashMap
DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
meta name="viewport" content="width=device-width, initial-scale=1.0">
meta http-equiv="X-UA-Compatible" content="ie=edge">
title>Documenttitle>
head>
body>
Welcomebr/>input id="text" type="text"/>
button onclick="send()">发送消息button>
hr/>
button onclick="closeWebSocket()">关闭WebSocket连接button>
hr/>
div id="message">div>
body>
script>
var websocket = null;
//判断当前浏览器是否支持WebSocket
if (‘WebSocket‘ in window) {
websocket = new WebSocket("ws://localhost:8080/demo/imserver/11");
}
else {
alert(‘当前浏览器 Not support websocket‘)
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById(‘message‘).innerHTML += innerHTML + ‘
‘;
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById(‘text‘).value;
websocket.send(message);
}
script>
html>
文章标题:Springboot websocket学习Demo
文章链接:http://soscw.com/index.php/essay/57336.html