美文网首页
springboot2实现Websocket前后端通信

springboot2实现Websocket前后端通信

作者: IT小池 | 来源:发表于2022-05-12 10:54 被阅读0次

首先导包:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
</dependencies>

接着创建 WebSocketConfig配置类

package com.example.demo.websocket.config;

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

/**
 * @author xiaochi
 * @date 2022/5/12 9:51
 */
@Configuration
public class WebSocketConfig {

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

继续创建 WebsocketServer 服务

package com.example.demo.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xiaochi
 * @date 2022/5/12 9:53
 */
@Slf4j
@Component
@ServerEndpoint("/api/ws/{userId}")
public class WebsocketServer{

    private static ConcurrentHashMap<String, Session> resources = new ConcurrentHashMap<>();

    /**
     * 进入链接
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        log.info("【用户"+userId+"加入链接成功】");
        if (resources.containsKey(userId)){
            resources.remove(userId);
            resources.put(userId,session);
            return;
        }
        resources.put(userId,session);
    }

    /**
     * 收到客户端消息并且群发消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        log.info("【收到消息】:{}",message);
        sendMessage(message);
    }

    /**
     * 断开链接
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId){
        log.info("关闭链接:{}",userId);
        resources.remove(userId);
    }

    /**
     * 链接错误
     * @param userId
     * @param error
     */
    @OnError
    public void onError(@PathParam("userId") String userId,Throwable error){
        log.error("【用户"+userId+"链接错误】,{}",error);
    }

    /**
     * 单发消息
     * @param message
     */
    public static void sendMessage(String userId,String message) throws IOException {
        if (resources.containsKey(userId)){
            resources.get(userId).getBasicRemote().sendText(message);
        }
    }

    /**
     * 群发消息
     * @param message
     */
    public static void sendMessage(String message){
        for (Session session : resources.values()){
            try {
                session.getBasicRemote().sendText("群发消息:"+message);
            }catch (Exception e){
                continue;
            }
        }
    }
}

ok,到此完成,接下来就是测试接口实现推送前端消息 WebsocketController

package com.example.demo.websocket.controller;

import com.example.demo.websocket.server.WebsocketServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaochi
 * @date 2022/5/12 10:30
 */
@RestController
public class WebsocketController {

    /**
     * 服务端推送消息接口
     * @param msg
     * @return
     */
    @GetMapping("/websocket/{msg}")
    public String sendMessage(@PathVariable String msg){
        WebsocketServer.sendMessage(msg);
        return "ok: "+ msg;
    }
}

前端js

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div id="message"></div>
<div>
    <input type="text" id="text">
    <button id="send">发送</button>
</div>

<script>
    window.onload = function () {
        /************ websocket前端 ************/
        var websocket;
        if('WebSocket' in window) {
            websocket = new WebSocket('ws://localhost:8080//api/ws/'+50000);
        }else {
            alert('该浏览器不支持websocket!');
        }
        websocket.onopen = function (event) {
            console.log('建立连接');
        }
        websocket.onclose = function (event) {
            console.log('连接关闭');
        }
        websocket.onmessage = function (event) {
            console.log('收到消息:' + event.data)
            //弹窗提醒, 播放音乐
            document.getElementById('message').innerText = event.data;
        }
        websocket.onerror = function () {
            alert('websocket通信发生错误!');
        }
        // 窗口关闭事件,关闭窗口的时候关闭 websocket事件
        window.onbeforeunload = function () {
            websocket.close();
        }
        document.getElementById("send").onclick = function () {
            console.log(document.getElementById("text").value);
            websocket && websocket.send(document.getElementById("text").value)
        }
    }
</script>
</body>
</html>

OK,完成了

相关文章

网友评论

      本文标题:springboot2实现Websocket前后端通信

      本文链接:https://www.haomeiwen.com/subject/wxusurtx.html