不废话直接上代码
后端
一、引入WebSocket依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
二、编写WebSocket配置类
import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @ClassName WebSocketConfig * @Description WebSocket配置类 * @Author 翟文彪 * @Date 2022/1/6 0:12 * @Version 1.0 */ @Component public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
三、编写WebSocket业务类
WebSocket业务类我选择写在Service层,但是它又属于一种特殊的Service,注意看下面代码中类上方的注解。
import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.util.concurrent.CopyOnWriteArraySet; /** * @ClassName WebSocket * @Description WebSocket实现(一个特殊的service) * @Author 翟文彪 * @Date 2022/1/6 0:15 * @Version 1.0 */ @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消息,有新的连接"); } @OnClose public void onClose(){ webSocketSet.remove(this); log.info("webSocket消息,连接断开"); } @OnMessage public void onMessage(String message){ log.info("webSocket消息,收到客户端发来的消息",message); } public void sendMessage(String message){ for (WebSocket webSocket: webSocketSet){ log.info("webSocket消息,广播消息",message); try { webSocket.session.getBasicRemote().sendText(message); }catch (Exception e){ e.printStackTrace(); } } } }
@ServerEndpoint 中的地址就是需要前端调取的接口地址。
前端
一、连接后端WebSocket
<script> var websocket = null; if('WebSocket' in window){ websocket = new WebSocket('ws://你的IP地址:你的端口号/webSocket'); }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 (){ alert('websocket通信发生错误!') } windows.onbeforeunload = function(){ websocket.close() } </script>
实现
做完以上步骤操作后,我们可以直接在springboot项目中,在你想发送消息的实现类中@Autowired 你编写的WebSocket业务类,然后调用sendMessage方法即可实现发送消息。
例:
@Autowired private WebSocket webSocket; public void method(){ // 具体方法实现 ************** // 发送WebSocket消息 webSocket.sendMessage("success"); }
当这个方法执行后,前端能收到“success”则发送消息成功。