1.添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2.前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>webscoket</title> </head> <body> <script> var websocket = null; if('WebSocket' in window){ websocket = new WebSocket("ws://localhost:8080/webSocket") }else{ alert("该浏览器不支持websocket") } websocket.onopen = function(event){ console.log('建立连接') } websocket.onclose = function(event){ console.log('连接关闭') } websocket.onmessage = function(event){ console.log('收到消息:'+event.data) document.body.innerHTML=event.data } websocket.onerror = function(){ alert("websocket发生通信错误") } websocket.onbeforeunload = function(event){ websocket.close() } </script> </body> </html>
3.后台代码
WebSocketConfig.java
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Component public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
WebSocket.java
package com.example.demo; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; @Component @ServerEndpoint("/webSocket") 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); System.err.println("【websocket消息】 有新的连接,总数:"+webSocketSet.size()); } @OnClose public void onClose() { webSocketSet.remove(this); System.err.println("【websocket消息】 连接断开,总数:"+webSocketSet.size()); } @OnMessage public void onMessage(String message) { System.err.println("【websocket消息】收到客户端发来的消息"+message); } public void sendMessage(String message) { for(WebSocket webSocket:webSocketSet) { System.err.println("【websocket消息】广播消息,message="+message); try { webSocket.session.getBasicRemote().sendText(message); }catch(Exception e) { e.printStackTrace(); } } } }
Controller.java
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @Autowired WebSocket websocket; @RequestMapping("/send") public String send(String message) { websocket.sendMessage(message); return "测试成功"; } }