SpringBoot整合WebSocket初體驗
抱歉,當時整理的太亂了,我以后有時間重新整理一下,注釋很雜亂,但是可以跑起來,記得修改端口號,html文件中默認為8080,勉強可以做參考
1. 新建項目:
然后手動引一下fastjson就ok了
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency>
2. 項目結構

所有文件就是這么個擺放
3. 文件:
WebSocketConfig.java
package kim.nzxy.websocketdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Author: Xiaoyan
* @Date: 2019/5/27 12:49
*/
@Configuration
public class WebSocketConfig {
/**
* 支持websocket
*/
@Bean
public ServerEndpointExporter createServerEndExporter() {
return new ServerEndpointExporter();
}
/**
* 跨域過濾器
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
}
PageController.java
package kim.nzxy.websocketdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author: Xiaoyan
* @Date: 2019/5/27 15:28
*/
@Controller
public class PageController {
@RequestMapping("customer")
public String customer() {
return "customer";
}
@RequestMapping("official")
public String official() {
return "official";
}
}
Message.java
package kim.nzxy.websocketdemo.entity;
import lombok.Data;
/**
* 這里的Message類並不切合應用,僅僅是為了演示發送一個數據對象
* 但是我想不出來拿什么舉例子了,我項目中實際需要的代碼需要保密
* 如果是純文本,則會簡單很多,自己去百度WebSocket做一個發消息的東西就好了
*
* @Author: Xiaoyan
* @Date: 2019/5/27 12:53
*/
@Data
public class Message {
private Integer id;
private String theme;
private String content;
private String official;
private String customer;
}
MessageDecoder.java
package kim.nzxy.websocketdemo.entity;
import com.alibaba.fastjson.JSON;
import kim.nzxy.websocketdemo.entity.Message;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
/**
* json2Company
*
* @author xy
*/
public class MessageDecoder implements Decoder.Text<Message> {
@Override
public void destroy() {
}
@Override
public void init(EndpointConfig arg0) {
}
@Override
public Message decode(String user) {
return JSON.parseObject(user, Message.class);
}
@Override
public boolean willDecode(String arg0) {
return true;
}
}
MessageEncoder
package kim.nzxy.websocketdemo.entity;
import com.alibaba.fastjson.JSON;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
/**
* json2Company
*
* @author xy
*/
public class MessageEncoder implements Encoder.Text<Message> {
@Override
public void destroy () {
}
@Override
public void init (EndpointConfig arg0) {
}
@Override
public String encode (Message object) throws EncodeException {
return JSON.toJSONString(object);
}
}
TestWebSocket.java
package kim.nzxy.websocketdemo.ws;
import kim.nzxy.websocketdemo.entity.Message;
import kim.nzxy.websocketdemo.entity.MessageDecoder;
import kim.nzxy.websocketdemo.entity.MessageEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author xy
* @ServerEndpoint 注解是一個類層次的注解,它的功能主要是將目前的類定義成一個websocket服務器端,
* 注解的值將被用於監聽用戶連接的終端訪問URL地址,客戶端可以通過這個URL來連接到WebSocket服務器端
* @ServerEndpoint 可以把當前類變成websocket服務類
* id:當前登錄對象
* receive:
*/
@ServerEndpoint(value = "/ws/{role}", decoders = MessageDecoder.class, encoders = MessageEncoder.class)
@Component
@Slf4j
public class TestWebSocket {
/**
* 靜態變量,用來記錄當前客服人員在線連接數。應該把它設計成線程安全的。
*/
private static int official = 0;
/**
* 同上 客戶
*/
private static int customer = 0;
/**
* concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通信的話,可以使用Map來存放,其中Key可以為用戶標識
*/
private static ConcurrentHashMap<String, TestWebSocket> webSocketMapA = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, TestWebSocket> webSocketMapB = new ConcurrentHashMap<>();
/**
* 與某個客戶端的連接會話,需要通過它來給客戶端發送數據
*/
private Session session;
/**
* 當前發消息的人員編號
*/
private String userId = "";
/**
* 當前發消息的人對應的開票員
*/
private java.lang.String receiveId = "";
private static synchronized void addA() {
official++;
}
private static synchronized void addB() {
customer++;
}
private static synchronized void subA() {
official--;
}
private static synchronized void subB() {
customer--;
}
private static synchronized int getA() {
return official;
}
private static synchronized int getB() {
return customer;
}
/**
* 連接建立成功調用的方法
*
* @param session 可選的參數。session為與某個客戶端的連接會話,需要通過它來給客戶端發送數據
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "role") String role) {
this.session = session;
userId = UUID.randomUUID().toString();
// 在線數加1,a代表客服
if ("a".equals(role)) {
// 客服的id為數字,這樣就可以區分客服和用戶了,這里假設不會重復
// 這里隨機的用戶id,所以不方便重連,正式環境大概要和用戶表結合
addA();
webSocketMapA.put(userId, this);
} else {
userId = UUID.randomUUID().toString();
addB();
webSocketMapB.put(userId, this);
}
// 這里可以加一個判斷,如果webSocketMap.containsKey(id),則系統重新指定一個id
log.info("新連接: " + userId + "----當前客服人數:" + getA() + "----當前客戶人數:" + getB());
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
// 從map中刪除
if (webSocketMapA.containsKey(userId)) {
webSocketMapA.remove(userId);
// 在線數減1
subA();
log.info("客服下線:" + userId + "----當前客服人數:" + getA() + "----當前客戶人數:" + getB());
} else {
webSocketMapB.remove(userId);
subB();
log.info("客戶下線:" + userId + "----當前客服人數:" + getA() + "----當前客戶人數:" + getB());
}
}
/**
* 收到客戶端消息后調用的方法
*
* @param message 客戶端發送過來的消息
*/
@OnMessage
public void onMessage(Message message, @PathParam(value = "role") String role) {
System.out.println(message);
if ("a".equals(role)) {
receiveId = message.getCustomer();
if (message.getCustomer() == null || !webSocketMapB.containsKey(receiveId)) {
webSocketMapA.get(userId).sendMessage("客戶已下線");
} else {
webSocketMapB.get(receiveId).sendObj(message);
}
} else {
if (message.getOfficial() != null) {
if (webSocketMapA.containsKey(message.getOfficial())) {
webSocketMapA.get(message.getOfficial()).sendObj(message);
} else {
webSocketMapB.get(userId).sendMessage("當前客服已下線,請換個客服人員重新咨詢");
}
} else {
if (webSocketMapA.size() == 0) {
webSocketMapB.get(userId).sendMessage("當前無在線客服");
} else {
// 系統隨機指定客服,正式環境應當判斷客服接應人數然后再進行指配
int i = new Random().nextInt(webSocketMapA.size());
message.setOfficial(webSocketMapA.keySet().toArray(new String[0])[i]);
message.setCustomer(userId);
webSocketMapA.get(message.getOfficial()).sendObj(message);
}
}
}
}
/**
* 發生錯誤時調用
*/
@OnError
public void onError(Throwable error) {
log.info(error.toString());
}
/**
* 發送對象到客戶端
*/
private void sendObj(Message message) {
try {
this.session.getBasicRemote().sendObject(message);
} catch (EncodeException | IOException e) {
log.info("錯誤:由用戶" + userId + "向" + receiveId + message.toString() + "具體錯誤為:" + e.toString());
}
}
/**
* 發送文本到客戶端
*/
private void sendMessage(String message) {
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.info("錯誤:由用戶" + userId + "向" + receiveId + message + "具體錯誤為:" + e.toString());
}
}
}
WebSocketApplication.java
package kim.nzxy.websocketdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebsocketDemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketDemoApplication.class, args);
}
}
4. 前端代碼
前端代碼頗為簡單,而且可以抽取一個js文件,但是由於功能增加后肯定就不方便抽取了,而且為了看代碼方便,此處就保留這樣
customer.html
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>客戶的頁面</title>
</head>
<body>
<div id="hi">
</div>
<input placeholder="主題" type="text">
<input placeholder="內容" type="text">
<button onclick="send()" type="button">發送</button>
</body>
<script>
let websocket = null;
let LData = {};
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/ws/b");
} else {
alert('當前瀏覽器不支持\n請更換瀏覽器');
}
//發送消息
function send() {
let ins = document.getElementsByTagName("input");
LData['theme'] = ins[0].value;
LData['content'] = ins[1].value;
websocket.send(JSON.stringify(LData));
}
//接收到消息的回調方法
websocket.onmessage = function (event) {
let data = event.data;
console.log(data);
if ("{" === data.substr(0, 1)) {
LData = JSON.parse(data);
console.log('LData' + LData);
document.getElementById("hi").innerHTML += LData['theme'] + '----' + LData['content'] + '\n';
} else {
document.getElementById("hi").innerHTML += data + '\n';
}
};
//連接成功建立的回調方法
websocket.onopen = function () {
console.log("onopen...");
};
//連接關閉的回調方法
websocket.onclose = function () {
console.log("onclose...");
};
//連接發生錯誤的回調方法
websocket.onerror = function () {
alert("連接服務器失敗,請刷新頁面重試")
};
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
};
//關閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
</script>
</html>
official.html
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>客服的頁面</title>
</head>
<body>
<pre id="hi">
</pre>
<input placeholder="主題" type="text">
<input placeholder="內容" type="text">
<button onclick="send()" type="button">發送</button>
</body>
<script>
let websocket = null;
// 用來保留客戶信息用的
let LData = {};
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/ws/a");
} else {
alert('當前瀏覽器不支持\n請更換瀏覽器');
}
//發送消息
function send() {
let ins = document.getElementsByTagName("input");
LData['theme'] = ins[0].value;
LData['content'] = ins[1].value;
console.log(LData);
websocket.send(JSON.stringify(LData));
}
//接收到消息的回調方法
websocket.onmessage = function (event) {
let data = event.data;
console.log("收到:"+data);
if ("{" === data.substr(0, 1)) {
LData = JSON.parse(data);
console.table(LData);
document.getElementById("hi").innerHTML += LData['theme'] + '----' + LData['content'] + '\n';
} else {
document.getElementById("hi").innerHTML += data + '\n';
}
};
//連接成功建立的回調方法
websocket.onopen = function () {
console.log("onopen...");
};
//連接關閉的回調方法
websocket.onclose = function () {
console.log("onclose...");
};
//連接發生錯誤的回調方法
websocket.onerror = function () {
alert("連接服務器失敗,請刷新頁面重試")
};
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
};
//關閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
</script>
</html>
pom.xml(springboot版本用的是2019年12月4日 16:48:12的版本,代碼沒變):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

