webSocket的基本使用

Posted shouyaya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(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的基本使用的主要内容,如果未能解决你的问题,请参考以下文章

html PHP代码片段: - AJAX基本示例:此代码演示了使用PHP和JavaScript实现的基本AJAX功能。

使用node.js和“ws”-package(API:bitfinex)了解基本的websocket API

websocket弹簧启动设置

NodeJS中的Websockets。从服务器端WebSocket客户端调用WebSocketServer

c_cpp Robolution基本代码片段

WebSocket - 关闭握手 Gorilla