客户端
<script>
//html5 监听
var websocket =null;
if('WebSocket' in window){
websocket= new WebSocket('ws://');
}else{
alert("浏览器不支持websocket");
}
websocket.onopen= function(event){
console.log('建立连接');
}
websocket.onclose= function(event){
console.log('关闭连接');
}
websocket.onmessage= function(event){
console.log('收到消息'+event.data);
}
websocket.onerror= function(event){
console.log('websocket通讯发生错误');
}
window.onbeforeunload=function () {
websocket,close();
}
</script>
前端js包外部地址: cdn.bootcss.com
后端
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置
@Component
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
通常把websocket 类写到 server 层中
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
}
@OnMessage
public void onMessage(String message) {
log.info("【websocket消息】收到客户端发来的消息:{}", message);
}
public void sendMessage(String message) {
for (WebSocket webSocket: webSocketSet) {
log.info("【websocket消息】广播消息, message={}", message);
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在需要发消息的地方发送消息
@Autowired
private WebSocket webSocket;
//发送websocket消息
webSocket.sendMessage(orderDTO.getOrderId());