其他分享
首页 > 其他分享> > 如何使用websocket实现推送信息到客户端

如何使用websocket实现推送信息到客户端

作者:互联网

文章目录

后端项目

配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
server:
  port: 8085

配置包

在这里插入图片描述

WebSocketConfig

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

WebSocketServer

@Setter
@Getter
// ServerEndpointExporter bean扫描ServerEndpoint,这个注解和我们之前用的requestMapping相似
@ServerEndpoint("/{uuid}")
@Component
public class WebSocketServer {
    private Session session;
    public static ConcurrentHashMap<String,WebSocketServer> clients = new ConcurrentHashMap<>();
    /**
     *  onOpen 当客户端和服务端建立连接的时候会触发 onOpen方法
     *  onClose: 当客户端和服务端断开连接的时候会触发onClose 方法
     *  one rror: 当客户端和服务端建立连接的时候出了问题会触发
     *  onMessage: 当客户端服务器发送数据的时候会被触发
     */
    @OnOpen
    public void onOpen(Session session, @PathParam( "uuid") String uuid){
        System.out.println("客户端连接===>"+uuid);
        this.session = session;
        clients.put(uuid,this);
    }
    @OnClose
    public void onClose(@PathParam( "uuid") String uuid){
        clients.remove(uuid);
    }
    @OnError
    public void one rror(Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String msg){
        System.out.println(msg);
    }
}

控制器接口测试

@RestController
public class SendMsg {

    @RequestMapping("/sendMsg")
    public String sendMsg(String msg,String token) throws IOException {
//        根据token找到客户端 给客户端去推送数据
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        webSocketServer.getSession().getBasicRemote().sendText(msg);
        return "发送成功";
    }
}

前端项目

socket.js

function createScoket(token){
    var socket;
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        var host = window.location.origin.replace("http:","ws:")
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket("ws://localhost:8085/"+token);
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(result) {
         console.log(result);
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            console.log("Socket发生了错误");
        }
        //窗口关闭
        $(window).unload(function(event){
            socket.close();
        });
    }
    return socket;
}

网页代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/socket.js"></script>
    <script src="js/jquery.js"></script>
</head>
<body>
        <input type="button" value="建立连接" onclick="con()"/>
        <input type="text" id="msg">
        <input type="button" value="发送数据" onclick="sendMsg()">
</body>
<script>
    var socket;
    function con() {
        if (!socket){
            socket = createScoket(123);
        }
    }

    function sendMsg() {
            var msg = $("#msg").val();
            socket.send(msg);
    }
</script>
</html>

功能测试

前端(客户端)推送信息给后端

后端推送数据给前端(客户端)

@RestController
public class SendMsg {

    @RequestMapping("/sendMsg")
    public String sendMsg(String msg,String token) throws IOException {
//        根据token找到客户端 给客户端去推送数据
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        webSocketServer.getSession().getBasicRemote().sendText(msg);
        return "发送成功";
    }
}

标签:websocket,socket,WebSocketServer,token,推送,public,客户端
来源: https://blog.csdn.net/EDT777/article/details/114537721