SpringBoot整合WebSocket
1.搭建一个的SpringBoot项目
2.导入WebSocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
3.添加配置类
具体代码如下
package com.example.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @date 2019/9/25 15:29
* @author ww
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4.添加一个配置WebSocket的服务类
具体代码如下
package com.example.websocket.ws;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* websocket服务类
* @date 2019/9/25 15:30
* @author ww
*/
@ServerEndpoint(value = "/webSocket")
@Component
public class WebSocketServer {
/**
* 在线数 静态变量,用来记录当前在线连接数,应该把它设计出线程安全的
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的websocket对象
*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 日志
*/
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* 连接建立成功后调用的方法
* @param session 可选的参数,session为与某个客户端的连接会话
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
log.info("有新的连接加入!当前连接数为:{}",getOnlineCount());
try {
sendMessage("连接成功");
}catch (IOException e) {
log.error("websocket异常" + e.getMessage());
}
}
/**
* 关闭连接时调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
log.info("有一个连接关闭!当前连接数为:{}",getOnlineCount());
}
/**
* 消息发送
* @param msg 消息
* @throws IOException 发送出现异常
*/
public void sendMessage(String msg) throws IOException {
session.getBasicRemote().sendText(msg);
}
/**
* 发送错误
* @param error 错误信息
*/
@OnError
public void onError(Throwable error) {
log.info("发生错误:{}",error.getMessage());
}
/**
* 收到客户端的消息后调用的方法
* @param message 客户端发来的消息
*/
@OnMessage
public void onMessage(String message) {
log.info("来自客户端的消息:{}",message);
//消息群发
webSocketSet.forEach( item -> {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* 获取在线数
* @return 返回在线数
*/
private static synchronized int getOnlineCount() {
return onlineCount;
}
/**
* 新增在线数
*/
private static synchronized void addOnlineCount() {
onlineCount ++;
}
/**
* 减少在线数
*/
private static synchronized void subOnlineCount() {
onlineCount--;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true;}
if (o == null || getClass() != o.getClass()) { return false;}
WebSocketServer that = (WebSocketServer) o;
return Objects.equals(session, that.session);
}
@Override
public int hashCode() {
return Objects.hash(session);
}
}
5.测试
创建一个html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WebSocket Echo Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<script src='https://code.jquery.com/jquery-3.4.1.min.js'></script>
<script>
var ws = new WebSocket("ws://localhost:8081/webSocket");
ws.onopen = function (e) {
console.log('Connection to server opened');
}
function sendMessage() {
ws.send($('#message').val());
}
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert(received_msg);
};
ws.onclose = function(){
// 关闭 websocket
alert("连接已关闭...");
};
ws.onerror = function(err) {
alert("Error: " + err);
};
</script>
</head>
<body >
<div class="vertical-center">
<div class="container">
<p> </p>
<form role="form" id="chat_form" onsubmit="sendMessage(); return false;">
<div class="form-group">
<input class="form-control" type="text" name="message" id="message"
placeholder="Type text to echo in here" value="" />
</div>
<button type="button" id="send" class="btn btn-primary"
onclick="sendMessage();">
Send!
</button>
</form>
</div>
</div>
</body>
</html>