码迷,mamicode.com
首页 > Web开发 > 详细

webSocket的基本使用

时间:2020-07-05 17:06:59      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:ref   func   var   case   open   弹窗   order   class   message   

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(WebSocketin 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();
            }
        }
    }
}

 

webSocket的基本使用

标签:ref   func   var   case   open   弹窗   order   class   message   

原文地址:https://www.cnblogs.com/shouyaya/p/13246494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!