package com.tl.erp.buss.controller.yzq.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author 1091
* @date 2023/2/16 11:22
*/
@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {
/**
* 与客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 存放客户端容器
*/
private static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
/**
* 用来存在线连接数
*/
private static final Map<String, Session> sessionPool = new HashMap<String, Session>();
/**
* 链接成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId) {
try {
this.session = session;
webSockets.add(this);
sessionPool.put(userId, session);
log.info("websocket消息: 有新的连接,总数为:" + webSockets.size());
} catch (Exception e) {
}
}
/**
* 收到客户端消息后调用的方法
*/
@OnMessage
public void onMessage(String message) {
log.info("websocket消息: 收到客户端消息:" + message);
}
/**
* 此为单点消息
*/
public void sendOneMessage(String userId, String message) {
Session session = sessionPool.get(userId);
if (session != null && session.isOpen()) {
try {
log.info("websocket消: 单点消息:" + message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 此为单点消息(多人)
*/
public void sendMoreMessage(String[] userIds, String message) {
for (String userId : userIds) {
Session session = sessionPool.get(userId);
if (session != null && session.isOpen()) {
try {
log.info("【websocket服务端】 单点消息:" + message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
package com.tl.erp.buss.controller.yzq.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author 1091
* @date 2023/2/16 11:15
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig {
/**
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.tl.erp.buss.controller.yzq;
import com.tl.erp.buss.controller.yzq.WebSocket.WebSocketServer;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author 1091
* @date 2023/2/16 11:23
*/
@RestController
@RequestMapping("/socket")
public class WebsocketController {
@Resource
private WebSocketServer webSocketServer;
/**
* 发送消息
*/
@GetMapping(path = "publish")
public String publish(String userId,String message,String a) {
//创建业务消息信息
webSocketServer.sendOneMessage(userId, message);
return "success";
}
}
如果有报错请加
package com.tl.erp.buss.controller.yzq.config;
/**
* @author 1091
* @date 2023/2/16 11:42
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class ScheduledConfig {
@Bean
public TaskScheduler taskScheduler(){
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(10);
taskScheduler.initialize();
return taskScheduler;
}
}
前端代码
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>未读消息</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js" type="text/javascript"></script>
<script>
var ws = new WebSocket('ws://127.0.0.1:8081/websocket/10086');
// 监听是否连接成功
ws.onopen = function () {
console.log('ws连接状态:' + ws.readyState);
// 连接成功则发送一个数据
ws.send('ok');
}
// 接听服务器发回的信息并处理展示
ws.onmessage = function (data) {
$("#arrivedDiv").append("<br/>"+data.data);
var count = $("#count").text();
count = Number(count) + 1;
$("#count").text(count);
// 完成通信后关闭WebSocket连接
//ws.close();
}
// 监听连接关闭事件
ws.onclose = function () {
// 监听整个过程中websocket的状态
console.log('ws连接状态:' + ws.readyState);
}
// 监听并处理error事件
ws.onerror = function (error) {
console.log(error);
}
function sendMessage() {
var content = $("#message").val();
$.ajax({
url: 'http://127.0.0.1:8081/socket/publish?userId=10086&message='+content+'&a=' +Math.random(),
type: 'GET',
dataType: 'jsonp',
async:false,
cache:false,
success: function (data) {
console.log(data +'成功')
}
})
}
</script>
</head>
<body>
<div>
<ul>
<li class="active"><i class="fa fa-home fa-lg"></i> 未读消息 <span id="count" class="unread">0</span></li>
</ul>
<div style="margin-left: 800px;">
<input style="height: 25px; width: 180px;" maxlength="60" value="" id="message"/>
<button class="button" id="mySendBtn" onclick="sendMessage()"> 点击发送</button>
<div style="font-size: 20px;color: darkcyan"> 接收到的websocket消息</div>
<hr/>
<div id="arrivedDiv" style="height:200px; width:300px; overflow:scroll; background:#EEEEEE;">
<br/>
</div>
</div>
</div>
</body>
</html>
效果图