首页 > 其他分享 >WebSocket 使用记录

WebSocket 使用记录

时间:2023-03-03 15:35:25浏览次数:43  
标签:WebSocket 记录 public session 使用 import id webSocket

WebSocket 主要解决的问题是 后端数据更新主动像前端推送数据

所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

开启Websocket 支持
package com.example.dome;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.server.ServerEndpoint;

/**
 * @author SPC-044
 * @date 13:39
 * @Version 1.0
 */

@Configuration
public class WebSocketConfig {

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

  

WebSocket  拦截服务类 
package com.example.dome;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author SPC-044
 * @date 10:57
 * @Version 1.0
 */
@ServerEndpoint("/webSocket/{id}")
@RestController
public class WebSocket {

    private static final Logger loger = LoggerFactory.getLogger(WebSocket.class);

    private static volatile int onlineCount = 0;

//    private static CopyOnWriteArraySet<WebSocket> webSocketSet =new CopyOnWriteArraySet();

    private String id;
    private static ConcurrentHashMap<String,WebSocket> webSocketMap = new ConcurrentHashMap();

    private Session session;
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id){ //新建连接时调用
        this.session=session;
        this.id =id;
        webSocketMap.put(id,this);
//        webSocketSet.add(this);
        loger.info("openWebSocket id={},name={}",id);
    }

    @OnClose
    public void onClose(){  //关闭链接时调用
        if(webSocketMap.containsKey(id)){
            webSocketMap.remove(id);
        }
//        webSocketSet.remove(this);

        loger.info("closeWebSocket。。。");
    }

    @OnMessage
    public void onMessage(String messsge,Session session){ //接受前端消息
        loger.info("收到消息{}",messsge);
        try {

//            sendMessage(messsge);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void one rror(Session session,Throwable error){ //链接异常时访问
        loger.info("链接错误");
    }

    private void sendMessage(String message) throws Exception {
        if(this.session.isOpen()){
            this.session.getBasicRemote().sendText(message);
        }
    }

    public static void sendInfo(String id,String message){ // 后端主动像前端推消息
        if(webSocketMap.get(id) !=null && webSocketMap.containsKey(id)){
            try {
                webSocketMap.get(id).sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            loger.info("该用户不在线!");
        }
    }
}

  

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>123</p>
<button name="test" value="模拟建立链接" onclick="lianjie()" >test</button>
</body>

<script type="text/javascript">
    // 加载页面时生成随机数模拟不同用户的 Id 
    var id = Math.ceil(Math.random()*10);
    console.log(id);
    function lianjie() {
        send();
    }
    // 加载页面时 建立链接 id 用于区分不同用户
    var webSocket  = new WebSocket("ws://127.0.0.1:8082/webSocket/"+id);

    webSocket.onerror = function () {
        console.log("链接错误");
    }

    webSocket.onopen = function () {
        console.log("链接成功");
    }

    webSocket.onmessage =function (event) {
        console.log(event.data);
    }

    webSocket.onclose = function () {
        console.log("关闭链接");
    }

    function closeWebSocket() {
        webSocket.close();
    }

    function send() {
        webSocket.send("第一次发消息");
    }
    
</script>
</html>

 

后端主动像前端推送消息

 WebSocket.sendInfo("10", "id 10 你好"); 传入 用户id 及消息
    @RequestMapping("/webSocketTest")
    public void websocketTest(){

        Thread thread = new Thread(() -> {
            WebSocket.sendInfo("1", "id 1 你好");
        });


        Thread thread1 = new Thread(() -> {
            WebSocket.sendInfo("10", "id 10 你好");
        });

        thread.start();
        thread1.start();

    }

 

标签:WebSocket,记录,public,session,使用,import,id,webSocket
From: https://www.cnblogs.com/wangfl/p/17175784.html

相关文章