webSocket的基本使用

1.引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2.在前端页面编写WebSocket的js代码

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
    var webSocket=null;
    if(‘WebSocket‘in window){
        //使用WebSocket要使用ws协议,将http替换成ws
        webSocket=new WebSocket(‘ws://shouyaya.natapp1.cc/sell/webSocket‘);
    }else{
        alert(‘你的浏览器不支持webSocket‘);
    }
    webSocket.onopen=function (event) {
        console.log(‘建立连接‘);
    }
    webSocket.onclose=function (event) {
        console.log(‘断开连接‘);
    }
    webSocket.onmessage=function (event) {
        //弹窗和播放音乐
        $(‘#Mymodal‘).modal(‘show‘);
        document.getElementById(‘orderSong‘).play();

    }
    webSocket.onerror=function (event) {
        console.log(‘webSocket发生错误‘);
    }
    window.onbeforeunload=function () {
        webSocket.close();
    }

</script>

3.配置WebSocket的配置类,具体原因:https://blog.csdn.net/qq_24283811/article/details/80584879?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase

@Component
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

4.编写WebSocket类

@Component
@Slf4j
@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);
        log.info("新建连接,总数为{}", webSocketSet.size());
    }

    @OnClose
    public void onClose(Session session) {
        webSocketSet.remove(this);
        log.info("断开连接,总数为{}", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到消息,消息为{}", message);
    }

    //广播消息,给每个WebSocket都发送消息
    public void sendMessage(String message) {
        for (WebSocket webSocket : webSocketSet) {
            log.info("发送消息,消息为{}", message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}