H5 webSocket使用

Posted qukaige

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了H5 webSocket使用相关的知识,希望对你有一定的参考价值。

前端代码:

<script>
    var websocket = null;
    if(‘WebSocket‘ in window) {
        websocket = new WebSocket(‘ws://sell.natapp4.cc/sell/webSocket‘);
    }else {
        alert(‘该浏览器不支持websocket!‘);
    }

    websocket.onopen = function (event) {
        console.log(‘建立连接‘);
    }

    websocket.onclose = function (event) {
        console.log(‘连接关闭‘);
    }

    websocket.onmessage = function (event) {
        console.log(‘收到消息:‘ + event.data)
        //弹窗提醒, 播放音乐
        $(‘#myModal‘).modal(‘show‘);

        document.getElementById(‘notice‘).play();
    }

    websocket.onerror = function () {
        alert(‘websocket通信发生错误!‘);
    }

    window.onbeforeunload = function () {
        websocket.close();
    }

</script>

 

后端代码:

1.引入pom文件

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

2.配置config

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

3.配置controller

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;


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

}

  

以上是关于H5 webSocket使用的主要内容,如果未能解决你的问题,请参考以下文章

h5 websocket 是如何工作的

H5新特性websocket

Node + H5 + WebSocket + Koa2 实现简单的多人聊天

spring boot Websocket(使用笔记)

Spring Boot SockJS应用例子

手写一个 WebSocket 协议