java后端+前端使用websocket实现消息推送(代码片段)

零 零     2022-12-16     156

关键词:

java后端+前端使用WebSocket实现消息推送(流程+详细代码)


在项目的开发时,遇到实现服务器主动发送数据到前端页面的功能的需求。实现该功能不外乎使用轮询和websocket技术,但在考虑到实时性和资源损耗后,最后决定使用websocket。现在就记录一下用Java实现Websocket技术吧~
    Java实现Websocket通常有两种方式:1、创建WebSocketServer类,里面包含open、close、message、error等方法;2、利用Springboot提供的webSocketHandler类,创建其子类并重写方法。我们项目虽然使用Springboot框架,不过仍采用了第一种方法实现。

创建WebSocket的简单实例操作流程

1.引入Websocket依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.7.0</version>
        </dependency>

2.创建配置类WebSocketConfig

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

/**
 * 开启WebSocket支持
 */
@Configuration
public class WebSocketConfig 
    @Bean
    public ServerEndpointExporter serverEndpointExporter() 
        return new ServerEndpointExporter();
    

3.创建WebSocketServer

在websocket协议下,后端服务器相当于ws里面的客户端,需要用@ServerEndpoint指定访问路径,并使用@Component注入容器

@ServerEndpoint:当ServerEndpointExporter类通过Spring配置进行声明并被使用,它将会去扫描带有@ServerEndpoint注解的类。被注解的类将被注册成为一个WebSocket端点。所有的配置项都在这个注解的属性中
( 如:@ServerEndpoint(“/ws”) )

下面的栗子中@ServerEndpoint指定访问路径中包含sid,这个是用于区分每个页面


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/notice/userId")
@Component
@Slf4j
public class NoticeWebsocket 

    //记录连接的客户端
    public static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * userId关联sid(解决同一用户id,在多个web端连接的问题)
     */
    public static Map<String, Set<String>> conns = new ConcurrentHashMap<>();

    private String sid = null;

    private String userId;


    /**
     * 连接成功后调用的方法
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) 
        this.sid = UUID.randomUUID().toString();
        this.userId = userId;
        clients.put(this.sid, session);

        Set<String> clientSet = conns.get(userId);
        if (clientSet==null)
            clientSet = new HashSet<>();
            conns.put(userId,clientSet);
        
        clientSet.add(this.sid);
        log.info(this.sid + "连接开启!");
    

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() 
        log.info(this.sid + "连接断开!");
        clients.remove(this.sid);
    

    /**
     * 判断是否连接的方法
     * @return
     */
    public static boolean isServerClose() 
        if (NoticeWebsocket.clients.values().size() == 0) 
            log.info("已断开");
            return true;
        else 
            log.info("已连接");
            return false;
        
    

    /**
     * 发送给所有用户
     * @param noticeType
     */
    public static void sendMessage(String noticeType)
        NoticeWebsocketResp noticeWebsocketResp = new NoticeWebsocketResp();
        noticeWebsocketResp.setNoticeType(noticeType);
        sendMessage(noticeWebsocketResp);
    


    /**
     * 发送给所有用户
     * @param noticeWebsocketResp
     */
    public static void sendMessage(NoticeWebsocketResp noticeWebsocketResp)
        String message = JSONObject.toJSONString(noticeWebsocketResp);
        for (Session session1 : NoticeWebsocket.clients.values()) 
            try 
                session1.getBasicRemote().sendText(message);
             catch (IOException e) 
                e.printStackTrace();
            
        
    

    /**
     * 根据用户id发送给某一个用户
     * **/
    public static void sendMessageByUserId(String userId, NoticeWebsocketResp noticeWebsocketResp) 
        if (!StringUtils.isEmpty(userId)) 
            String message = JSONObject.toJSONString(noticeWebsocketResp);
            Set<String> clientSet = conns.get(userId);
            if (clientSet != null) 
                Iterator<String> iterator = clientSet.iterator();
                while (iterator.hasNext()) 
                    String sid = iterator.next();
                    Session session = clients.get(sid);
                    if (session != null) 
                        try 
                            session.getBasicRemote().sendText(message);
                         catch (IOException e) 
                            e.printStackTrace();
                        
                    
                
            
        
    

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) 
        log.info("收到来自窗口"+this.userId+"的信息:"+message);
    

    /**
     * 发生错误时的回调函数
     * @param error
     */
    @OnError
    public void onError(Throwable error) 
        log.info("错误");
        error.printStackTrace();
    


封装了一个发送消息的对象可以直接使用

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel("ws通知返回对象")
public class NoticeWebsocketResp<T> 

    @ApiModelProperty(value = "通知类型")
    private String noticeType;

    @ApiModelProperty(value = "通知内容")
    private T noticeInfo;


4.websocket调用

一个用户调用接口,主动将信息发给后端,后端接收后再主动推送给指定/全部用户


@RestController
@RequestMapping("/order")
public class OrderController 
	@GetMapping("/test")
    public R test() 
    	NoticeWebsocket.sendMessage("你好,WebSocket");
        return R.ok();
    

前端WebSocket连接

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SseEmitter</title>
</head>
<body>
<div id="message"></div>
</body>
<script>
var limitConnect = 0;
init();
function init() 
var ws = new WebSocket('ws://192.168.2.88:9060/notice/1');
// 获取连接状态
console.log('ws连接状态:' + ws.readyState);
//监听是否连接成功
ws.onopen = function () 
    console.log('ws连接状态:' + ws.readyState);
    limitConnect = 0;
    //连接成功则发送一个数据
    ws.send('我们建立连接啦');

// 接听服务器发回的信息并处理展示
ws.onmessage = function (data) 
    console.log('接收到来自服务器的消息:');
    console.log(data);
    //完成通信后关闭WebSocket连接
    // ws.close();

// 监听连接关闭事件
ws.onclose = function () 
    // 监听整个过程中websocket的状态
    console.log('ws连接状态:' + ws.readyState);
reconnect();


// 监听并处理error事件
ws.onerror = function (error) 
    console.log(error);


function reconnect() 
    limitConnect ++;
    console.log("重连第" + limitConnect + "次");
    setTimeout(function()
        init();
    ,2000);
   

</script>
</html>

项目启动,打开页面后控制台打印连接信息

调用order/test方法后前端打印推送消息内容

这样,就可以接口或者ws调用网址的方式进行websocket的通信啦~
如果没有前端页面也可以使用在线WebSocket测试

OK,下课!!!

后端向前端推送消息

SpringBoot+WebSocket集成什么是WebSocket?为什么需要WebSocket?前言maven依赖WebSocketConfigWebSocketServer消息推送页面发起运行效果后续Websocker注入Bean问题netty-websocket-spring-boot-starterSpringboot2+Netty+WebsocketServerEndpointExpo 查看详情

springboot集成websocket,实现后台向前端推送信息(代码片段)

...xff0c;于是就使用到了MQTT,特此记录一下。一、什么是websocket?WebSocket协议是基于TCP的一种新的网络协议。它实现了客户端与服务器全双工通信,学过计算机网络 查看详情

springboot集成websocket,实现后台向前端推送信息(代码片段)

...xff0c;于是就使用到了MQTT,特此记录一下。一、什么是websocket?WebSocket协议是基于TCP的一种新的网络协议。它实现了客户端与服务器全双工通信,学过计算机网络 查看详情

前端页面实现报警器提示音效果

...后将消息推送到前台,(通过前端实时消息提示的效果-websocket长轮询),前台接受到消息后需要发出警报提示音,提醒用户。原理:很简单,使用html5里面的<audio>标签即可实现,在铃声的官网上选择一段报警的音频,放在... 查看详情

Java WebSocket 服务器 - 将消息推送到客户端

】JavaWebSocket服务器-将消息推送到客户端【英文标题】:JavaWebSocketserver-pushmessagetoclient【发布时间】:2017-02-1714:18:03【问题描述】:我有一个客户端/服务器websocket解决方案,但非常规,我希望服务器在未启动的情况下将更新推送... 查看详情

websocket前端发送一个消息后端还没执行完收不到第二条消息

参考技术A因为后端没有执行完,所以收不到第二条消息。前端即网站前台部分,运行在PC端,移动端等浏览器上展现给用户浏览的网页。随着互联网技术的发展,前端框架的应用,跨平台响应式网页设计能够适应各种屏幕分辨率... 查看详情

前端即时通信是怎么开发的?

前端即时通信可以通过WebSocket协议进行实现。以下是一些开发的步骤:了解WebSocket协议:WebSocket是一种持久化的协议,它建立在HTTP协议基础上。在WebSocket连接建立后,服务器和客户端之间可以互相发送和接收数据,而无需进行... 查看详情

基于go的websocket消息推送的集群实现

参考技术A目前websocket技术已经很成熟,选型Go语言,当然是为了节省成本以及它强大的高并发性能。我使用的是第三方开源的websocket库即gorilla/websocket。由于我们线上推送的量不小,推送后端需要部署多节点保持高可用,所以需... 查看详情

websocketsession共享

...了前端定时轮训调用接口来获取消息数据的方式,采用了WebSocket服务端推送。流程是首先前端跟后端应用新建一个连接,并携带当前登录的用户ID,此时WebSocket会创建一个WebsocketSession来唯一绑定该连接,我们会在后端用Map建立用... 查看详情

将结果从 RabbitMQ 队列推送到 CakePHP 前端

...一个系统,该系统由内置于CakePHP框架的前端和基于Java的后端组成。这两个生态系统之间的通信是通过从CakePHP控制器向RabbitMQ代理发送JSON消息来实现的。当消息被消费时,结果被发送回 查看详情

使用棘轮 php 将消息推送到 websockets 而没有 ZeroMQ

】使用棘轮php将消息推送到websockets而没有ZeroMQ【英文标题】:PushmessagetowebsocketswithratchetphpandwithoutZeroMQ【发布时间】:2018-08-1711:41:31【问题描述】:我尝试用棘轮和棘爪制作websocket服务器。我用ZeroMQhttp://socketo.me/docs/push阅读了文... 查看详情

springboot集成websocket,轻松实现信息推送!

...前端,于是就使用到了MQTT,特此记录一下。一、什么是websocket?WebSocket协议是基于TCP的一种新的网络协议。它实现了客户端与服务器全双工通信,学过计算机网络都知道,既然是全双工,就说明了服务器可以主动发送信息给客... 查看详情

后端消息推送-sse协议(代码片段)

...用ajax长轮询,而现在我们有了新的、更优雅的选择——WebSocket和SSE。WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。SSE是Server-SentEvents的简称,是一种服务器端到客户端(浏览器)的单项消息推送。对应的浏... 查看详情

.net后端使用signalr定时向前端vue推送消息(代码片段)

...alR是一个.NETCore/.NETFramework的开源实时框架,可以使用WebSocket、ServerSentEvents和LongPolling作为底层传输方式,包含服务端和客户端。WebSocket是最高效的传输方式,不过仅支持比较现代的浏览器,如果浏览器或Web服务器... 查看详情

.net后端使用signalr定时向前端vue推送消息(代码片段)

...alR是一个.NETCore/.NETFramework的开源实时框架,可以使用WebSocket、ServerSentEvents和LongPolling作为底层传输方式,包含服务端和客户端。WebSocket是最高效的传输方式,不过仅支持比较现代的浏览器,如果浏览器或Web服务器... 查看详情

前端监听websocket消息并实时弹出(代码片段)

...的操作按钮‘同意’、‘拒绝’等代码设计:1、使用websocket方式建立通道2、前端基于umi+antd+re 查看详情

websocket加layim实现在线聊天系统(代码片段)

...录用户。   2.前端layim监听消息发送,监听到通过websocketsend方法将消息对象发送至服务器  3.服务器接收到消息,通多消息对象获取接收者id,通过接收者id获取唯 查看详情

前端监听websocket消息并实时弹出(代码片段)

...的操作按钮‘同意’、‘拒绝’等代码设计:1、使用websocket方式建立通道2、前端基于umi+antd+reconnecting-websocket.js开发3、使用express+express-ws+mockjs建立websocket服务通道,模拟服务端推送消息运行效果:使用方... 查看详情