springboot中怎么使用websocket
其实使用方法网上有很多,但搞不懂这些人为什么手写冗余计数代码,而且加锁粒度还这么大,直接进入正题。
本文适合读者:会搭建springboot web 项目,会使用maven。
springboot相比spring而言所需配置少很多,废话不多说,代码如下
首先websocket所需pom如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Config配置类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.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.OnError;
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.springframework.stereotype.Component;
/**
* Type: WebSocketServer
* Description: 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!");
}
/**
* Title: onError
* Description: 发生错误时候回调函数
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
LOGGER.error("webSocket发生错误:" + error.getClass() + error.getMessage());
}
/**
* Title: sendMessage
* Description: 向客户端发送消息
* @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);
}
}
/**
* Title: getOnlineCount
* Description: 获取连接数
* @return
*/
public static int getOnlineCount() {
return webSocketSet.size();
}
}
(仅供测试↑)
html
(这使用的是thymeleaf模板,想直接用html可以把th部分去掉,改成自己的)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>WebSocket测试</title>
<meta charset="utf-8">
<script th:src="@{/js/jquery-3.3.1.min.js}"></script>
<script th:src="@{/js/sockjs.min.js}"></script>
</head>
<body>
<!-----start-main---->
<div class="main">
<h2>socketTest</h2>
<input type="button" id="send" value="点击向服务器发送消息">
<p id="recive"></p>
</div>
<!-----//end-main---->
</body>
<script type="text/javascript">
var ws = null;
var ws_status = false;
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!");
};
ws.onopen = function (event){
ws_status = true;
console.log("Connected!");
};
ws.onerror = function (event){
console.log("Connect error!");
};
}
//如果连接失败,每隔两秒尝试重新连接
setInterval(function(){
if(!ws_status){
openWebSocket();
}
}, 2000);
$("#send").click(function(){
ws.send("Hello, server, I am browser.");
});
</script>
</html>
GIT地址:https://github.com/ChinaLym/webpractice
前端很low,打开F12测试就会看到相应消息,支持断线重接。
若有问题,欢迎留言和指正!