本次使用的spring-boot版本: 2.1.1.RELEASE,后续其他文章皆基于此版本.
首先.要使用webSocket.需要构建终端服务.因为我们是使用spring-boot的内置容器.所以直接使用默认的ServerEndPointExporter即可
@Configuration
public class SytemConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
@Component
@ServerEndpoint(value = "/websocket")
public class WebSocketController {
private static int onlineCount = 0;
private static CopyOnWriteArraySet<Session> sessionSet = new CopyOnWriteArraySet();
@OnOpen
public void onOpen(Session session){
sessionSet.add(session);
addOnlineCount();
log.info("有新的会话加入{}", session.getId());
}
@OnClose
public void onClose(Session session){
sessionSet.remove(session);
log.info("有一个用户断开了连接");
}
@OnMessage
public void onMessage(String message, Session session) throws IOException{
log.info("来自客户端的消息--- {}:{}", session.getId(), message);
for (Session user : sessionSet){
if(user.isOpen() && user != session) {
user.getBasicRemote().sendText(message);
}
}
}
@OnError
public void onError(Session session, Throwable error){
log.error("socket发生错误了.{}", error.getMessage());
}
public void addOnlineCount(){
onlineCount++;
}
}
这边做了个简单的前端页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocketTestDemo1</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="chatWindow" style="width: 100%; height: 350px; border: 1px deepskyblue solid;">
</div>
<br>
<input type="text" class="msg"> <input type="button" value="发送">
</body>
</html>
<script>
var ws;
if("WebSocket" in window && ws == null){
ws = new WebSocket("ws://127.0.0.1:8080/websocket");
}else{
alert("您的浏览器不支持socket!");
}
$(function () {
$("input[type=button]").click(function () {
var msg = $("input[type=text]").val();
if(msg == null || msg.trim().length <= 0){return;}
sendMsg(msg);
})
})
ws.onopen = function (event) {
showMsg("连接已就绪,可以发送消息了");
}
ws.onmessage = function (p1) {
var data = p1.data;
showMsg(data);
}
ws.onclose = function (p1) {
showMsg("连接已已关闭....");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
ws.close();
}
function showMsg(msg) {
var a = "<span>" + msg + "</span><br/>"
$("#chatWindow").append(a);
}
function sendMsg(msg) {
ws.send(msg);
}
</script>
页面效果:
测试控制台效果:
这里我页面有个问题.我要是刷新页面.那么就会重新构建一个新的会话.所以我们如果需要在页面嵌入webSocket.最好是构建单页面站点.或者就只在首页面初始化websocket