WebSocketConfig
启用WebSocket的支持
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
maven依赖
<!-- socket依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- 客户端采用thymeleaf引擎模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
WebSocketServer
@Slf4j
@Component
@CrossOrigin
@ServerEndpoint("/wss/{tableId}")
public class OrderFoodSocketController {
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的
*/
private static int onlineCount = 0;
/**
* concurrent 包的线程安全Set,用来存放每个客户端对应的 myWebSocket对象
* 根据userId来获取对应的 WebSocket
*/
private static CopyOnWriteArraySet<OrderFoodSocketController> webSocketSet = new CopyOnWriteArraySet<OrderFoodSocketController>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收 tableId桌子id
*/
private String tableId = "";
/**
* 连接建立成功调用的方法
*
* @param session
* @param tableId
*/
@OnOpen
public void onOpen(Session session, @PathParam("tableId") String tableId) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
this.tableId = tableId;
try {
sendMessage(tableId + "开始点餐");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 客户端自动关闭连接
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 服务端关闭连接
* 根据请求参数判断是否关闭
*/
public static boolean closeWebSocket(String tableId){
for (OrderFoodSocketController item : webSocketSet) {
try {
if (item.tableId.equals(tableId)){
item.onClose();
}
} catch (Exception e) {
return false;
}
}
return true;
}
/**
* 发送自定义消息
* 根据项目业务逻辑操作
* @param picture 图片链接
* @param dishesName 餐品名称
* @param username 用户姓名
* @param tableId 桌子id
* @return
*/
public static boolean sendInfo(String picture, String dishesName, String username, String tableId) {
for (OrderFoodSocketController item : webSocketSet) {
try {
Map<String, Object> map = new HashMap<>();
map.put("picture", picture);
map.put("orderMessage", username + "点了" + dishesName);
String message = JSON.toJSONString(map);
if (tableId == null) {
item.sendMessage(message);
} else if (item.tableId.equals(tableId)) {
item.sendMessage(message);
}
} catch (IOException e) {
return false;
}
}
return true;
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.tableId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
private static synchronized int getOnlineCount() {
return onlineCount;
}
private static synchronized void addOnlineCount() {
OrderFoodSocketController.onlineCount++;
}
private static synchronized void subOnlineCount() {
OrderFoodSocketController.onlineCount--;
}
}
Controller
@RestController
public class SocketController {
@Autowired
WSUtils wsUtils;
@PostMapping("/sendInfo/{picture}/{dishesName}/{username}/{tableId}")
public boolean pushToWeb(@PathVariable(picture) String picture) {
return OrderFoodSocketController.sendInfo(picture, dishesName, username, tableId);
}
@GetMapping("page")
public ModelAndView page(){
return new ModelAndView("webSocket");
}
}
页面发起
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var socket;
function openSocket() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
/*
*根据自己ip端口来配置
*/
var socketUrl="ws://127.0.0.1:19020/wss/"+$("#tableId").val();
//var socketUrl="wss://kitchen.demo.wiseinfocloud.com"+$("#username").val()+"/"+$("#tableId").val();
console.log(socketUrl);
if(socket!=null){
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
setMessageInHtml(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
}
function setMessageInHtml(message){
document.getElementById('message').innerHTML += message + "<br/>" ;
}
function sendMessage() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
socket.send('{"tableId":"'+$("#tableId").val()+'","dishesName":"'+$("#dishesName").val()+'"}');
}
}
</script>
<body>
<p>【用户名】:<div><input id="username" name="username" type="text" value="10"></div>
<p>【桌号】:<div><input id="tableId" name="tableId" type="text" value="20"></div>
<p>【菜品名称】:<div><input id="dishesName" name="dishesName" type="text" value="hello websocket"></div>
<p>【操作】:<div><a onclick="openSocket()">开启socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div>
<div id="message"></div>
</body>
</html>
静态页面路径
测试
直接访问 localhost:8080/page 跳转到静态页面,根据业务逻辑修改调用Server层的sendInfo方法