springboot中怎么使用websocket
其实使用方法网上有很多,但搞不懂这些人为什么手写冗余计数代码,而且加锁粒度还这么大,直接进入正题。
本文适合读者:会搭建springboot web 项目,会使用maven。
springboot相比spring而言所需配置少很多,废话不多说,代码如下
首先websocket所需pom如下:
<dependency>
<groupId>org.spring work.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Config配置类:
import org.spring work.context.annotation.Bean;
import org.spring work.context.annotation.Configuration;
import org.spring work.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
后端:
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket. ;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring work.stereotype.Component;
/**
* Type: WebSocketServer
* De ion: WebSocketServer,实现服务器客户端平等交流,
* 达到服务器可以主动向客户端发生消息
* @author LYM
* @date Dec 18, 2018
*/
@ServerEndpoint(value = \"/websocket\")
@Component
public class WebSocketServer {
//日志记录器
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
//使用道格李的ConcurrentHashSet, 放的是WebSocketServer而不是session为了复用自己方法
private static transient volatile Set<WebSocketServer> webSocketSet = ConcurrentHashMap.newKeySet();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
sendMessage(\"连接成功\");
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
LOGGER.info(\"来自客户端(\" + session.getId() + \")的消息:\" + message);
sendMessage(\"Hello, nice to hear you! There are \" + webSocketSet.size() + \" users like you in total here!\");
}
/**
* :
* De ion: 发生错误时候回调函数
* @param session
* @param error
*/
@
public void (Session session, Throwable error) {
LOGGER.error(\"webSocket发生错误:\" + error.getClass() + error.getMessage());
}
/**
* : sendMessage
* De ion: 向客户端发送消息
* @param message
* @throws IOException
*/
public boolean sendMessage(String message) {
try {
this.session.getBasicRemote().sendText(message);
return true;
} catch (IOException error) {
LOGGER.error(\"webSocket-sendMessage发生错误:\" + error.getClass() + error.getMessage());
return false;
}
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message) {
LOGGER.info(\"webSocket-sendInfo群发消息:\" + message);
for (WebSocketServer item : webSocketSet) {
item.sendMessage(message);
}
}
/**
* : getOnlineCount
* De ion: 获取连接数
* @return
*/
public static int getOnlineCount() {
return webSocketSet.size();
}
}
(仅供测试↑)
html
(这使用的是thymeleaf模板,想直接用html可以把th部分去掉,改成自己的)
<!DOCTYPE html>
<html lang=\"en\" ns:th=\"http://www.thymeleaf.org\">
<head>
< >WebSocket测试</ >
< charset=\"utf-8\">
< th:src=\"@{/js/jquery-3.3.1.min.js}\"></ >
< th:src=\"@{/js/sockjs.min.js}\"></ >
</head>
<body>
<!-----start-main---->
<div class=\"main\">
<h2>socketTest</h2>
<input type=\"button\" id=\"send\" value=\"点击向服务器发送消息\">
<p id=\"recive\"></p>
</div>
<!-----//end-main---->
</body>
< type=\"text/ \">
var ws = null;
function openWebSocket(){
//判断当前浏览器是否支持WebSocket
if (\'WebSocket\' in window) {
ws = new WebSocket(\"ws://\"+window.location.host+\"/websocket\");
} else if (\'MozWebSocket\' in window) {
websocket = new MozWebSocket(\"ws://\"+window.location.host+\"/websocket\");
} else {
ws = new SockJS(\"http://\"+window.location.host+\"/websocket\");
}
ws.onopen = function () {
};
//这个事件是接受后端传过来的数据
ws.onmessage = function (event) {
//根据业务逻辑解析数据
console.log(\"Server:\");
console.log(event);
};
ws.onclose = function (event) {
console.log(\"Connection closed!\");
};
}
openWebSocket();
$(\"#send\").click(function(){
ws.send(\"Hello, server, I am browser.\");
});
</ >
</html>
前端很low,打开F12测试就会看到相应消息。
若有问题,欢迎留言和指正!
继续阅读与本文标签相同的文章
上一篇 :
gulp自动化构建工具
-
能力小访谈| 支付宝开放能力全方位助力白鲸鱼营销与内容安全
2026-05-18栏目: 教程
-
听众提建议,鼎城区城管局马上改
2026-05-18栏目: 教程
-
PARTsolutions让旺众/Wanzl的新设计缩短了2个多小时
2026-05-18栏目: 教程
-
第六届世界互联网大会将推出5G自动公交线路
2026-05-18栏目: 教程
-
市科技局加快黄石双创战略团队培育
2026-05-18栏目: 教程
