iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot实现WebSocket即时通讯的示例代码
  • 688
分享到

SpringBoot实现WebSocket即时通讯的示例代码

2024-04-02 19:04:59 688人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录1、引入依赖2、websocketConfig 开启WEBSocket3、WebSocketServer4、测试连接发送和接收消息5、在线测试地址6、测试截图1、引入依赖 <

1、引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastJSON</artifactId>
	<version>1.2.3</version>
</dependency>

2、WebSocketConfig 开启WebSocket

package com.shucha.deveiface.web.config;
 

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

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

3、WebSocketServer

package com.shucha.deveiface.web.ws;
 

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
 
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
 
@Component
@ServerEndpoint("/webSocket/{userId}")
@Slf4j
public class WebSocketServer {
    private Session session;
    private String userId;
    
    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
 
    
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap();
 
    
    private final static List<Session> SESSIONS = Collections.synchronizedList(new ArrayList<>());
 
    
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketSet.add(this);
        SESSIONS.add(session);
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
        } else {
            webSocketMap.put(userId,this);
            addOnlineCount();
        }
        // log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
        log.info("[连接ID:{}] 建立连接, 当前连接数:{}", this.userId, webSocketMap.size());
    }
 
    
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        // log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
        log.info("[连接ID:{}] 断开连接, 当前连接数:{}", userId, webSocketMap.size());
    }
 
    
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("[连接ID:{}] 错误原因:{}", this.userId, error.getMessage());
        error.printStackTrace();
    }
 
    
    @OnMessage
    public void onMessage(String message) {
        // log.info("【websocket消息】收到客户端发来的消息:{}", message);
        log.info("[连接ID:{}] 收到消息:{}", this.userId, message);
    }
 
    
    public void sendMessage(String message,Long userId) {
        WebSocketServer webSocketServer = webSocketMap.get(String.valueOf(userId));
        if (webSocketServer!=null){
            log.info("【websocket消息】推送消息, message={}", message);
            try {
                webSocketServer.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("[连接ID:{}] 发送消息失败, 消息:{}", this.userId, message, e);
            }
        }
    }
 
    
    public void sendMaSSMessage(String message) {
        try {
            for (Session session : SESSIONS) {
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                    log.info("[连接ID:{}] 发送消息:{}",session.getRequestParameterMap().get("userId"),message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
 
    
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
 
}

4、测试连接发送和接收消息

package com.shucha.deveiface.web.controller;
 
import com.alibaba.fastjson.JSONObject;
import com.shucha.deveiface.web.ws.WebSocketServer;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 

@RestController
@RequestMapping("/web")
public class TestWebSocket {
    @Autowired
    private WebSocketServer webSocketServer;
 
    
    @GetMapping("/test")
    public void test(){
        for (int i=1;i<4;i++) {
            WebsocketResponse response = new WebsocketResponse();
            response.setUserId(String.valueOf(i));
            response.setUserName("姓名"+ i);
            response.setAge(i);
            webSocketServer.sendMessage(JSONObject.toJSONString(response), Long.valueOf(String.valueOf(i)));
        }
    }
 
    
    @GetMapping("/sendMassMessage")
    public void sendMassMessage(){
        WebsocketResponse response = new WebsocketResponse();
        response.setUserName("群发消息模板测试");
        webSocketServer.sendMassMessage(JSONObject.toJSONString(response));
    }
 
    @Data
    @Accessors(chain = true)
    public static class WebsocketResponse {
        private String userId;
        private String userName;
        private int age;
    }
}

5、在线测试地址

websocket 在线测试

6、测试截图

访问测试发送消息:Http://localhost:50041//web/test

测试访问地址:ws://192.168.0.115:50041/webSocket/1   wss://192.168.0.115:50041/webSocket/2

 到此这篇关于SpringBoot实现WebSocket即时通讯的示例代码的文章就介绍到这了,更多相关SpringBoot WebSocket即时通讯内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot实现WebSocket即时通讯的示例代码

本文链接: http://www.lsjlt.com/news/145931.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringBoot实现WebSocket即时通讯的示例代码
    目录1、引入依赖2、WebSocketConfig 开启WebSocket3、WebSocketServer4、测试连接发送和接收消息5、在线测试地址6、测试截图1、引入依赖 <...
    99+
    2024-04-02
  • SpringBoot怎么实现WebSocket即时通讯
    这篇“SpringBoot怎么实现WebSocket即时通讯”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringBoo...
    99+
    2023-06-30
  • SpringBoot+WebSocket实现即时通讯的方法详解
    目录环境信息服务端实现导入依赖创建配置类创建一个注解式的端点并在其中通过配套注解声明回调方法服务端主动发送消息给客户端客户端实现Java客户端实现在前端环境(vue)中使用webso...
    99+
    2024-04-02
  • nodejs结合Socket.IO实现websocket即时通讯
    目录为什么要用 websocketSocket.io开源项目效果预览app.jsindex.html为什么要用 websocket websocket 是一种网络通信协议,一般用来进...
    99+
    2024-04-02
  • SpringBoot整合websocket实现即时通信聊天
    目录一、技术介绍1.1 客户端WebSocket1.1.1 函数1.1.2 事件1.2 服务端WebSocket二、实战 2.1、服务端2.1.1引入maven依赖2.1....
    99+
    2024-04-02
  • AndroidFlutter基于WebSocket实现即时通讯功能
    目录前言联系人界面构建聊天界面的实现消息界面的 MultiProvider运行效果前言 我们在前面花了很大篇幅介绍 Provider 状态管理,这是因为在 Flu...
    99+
    2024-04-02
  • SpringBoot整合Netty实现WebSocket的示例代码
    目录一、pom.xml依赖配置二、代码2.1、NettyServer 类2.2、SocketHandler 类2.3、ChannelHandlerPool 类2.4、Applicat...
    99+
    2024-04-02
  • C++实现即时通信的示例代码(直接运行)
    目录题目软件:VS服务器端客户端题目 由于本学期上了网络编程课程,老师要求写使用Socke实现网络编程。于是参考 C++多线程实现即时通信软件 写出了简单版本的没有界面的即时通信软件...
    99+
    2024-04-02
  • nodejs如何结合Socket.IO实现websocket即时通讯
    这篇文章给大家分享的是有关nodejs如何结合Socket.IO实现websocket即时通讯的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。为什么要用 websocketwebsocket 是一种网络通信协议,一...
    99+
    2023-06-25
  • SpringBoot中webSocket实现即时聊天
    即时聊天 这个使用了websocket,在springboot下使用很简单。前端是小程序,这个就比较坑,小程序即时聊天上线需要域名并且使用wss协议,就是ws+ssl更加安全。但是要...
    99+
    2024-04-02
  • php 怎么实现即时通讯实例
    本教程操作环境:windows7系统、PHP8.1版、Dell G3电脑。php 怎么实现即时通讯实例?仿百度商桥IM即时通讯(Laravel)基于workerman和websocket开发实时聊天系统仿百度商桥IM通讯实现原理及方法:1、...
    99+
    2024-04-02
  • php如何实现即时通讯实例
    本篇内容介绍了“php如何实现即时通讯实例”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!php实现即时通讯实例的方法:1、搭建websock...
    99+
    2023-07-04
  • Android Flutter基于WebSocket怎么实现即时通讯功能
    这篇文章主要介绍“Android Flutter基于WebSocket怎么实现即时通讯功能”,在日常操作中,相信很多人在Android Flutter基于WebSocket怎么实现即时通讯功能问题上存在疑惑,小编查阅了各...
    99+
    2023-06-29
  • SpringBoot中webSocket如何实现即时聊天
    这篇文章主要介绍了SpringBoot中webSocket如何实现即时聊天,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。springboot是什么springboot一种全新...
    99+
    2023-06-14
  • websocket结合node.js实现双向通信的示例代码
    首先我们需要了解,什么是websocket,它的作用和优势是什么,为什么要用它。 什么是websocket websocket是基于TCP的一种双向通信协议。在此之前,一直是采用轮询...
    99+
    2023-02-10
    websocket node.js双向通信 node.js双向通信
  • Spring Boot 实现 WebSocket 的代码示例
    目录什么是 WebSocket ?HTTP vs WebSocket什么时候使用 WebSocket?代码示例1. SpringBoot 使用原生 WebSocket1.1 引入 s...
    99+
    2024-04-02
  • 微信小程序如何使用WebSocket实现即时通讯
    使用WebSocket实现即时通讯功能,可以让用户实时收发消息,并保持连接状态。在微信小程序中,可以通过wx.connectSock...
    99+
    2024-04-03
    微信小程序 WebSocket
  • 300行代码实现go语言即时通讯聊天室
    学了2年Java,因为工作原因需要转Golang,3天时间学习了下go的基本语法,做这样一个聊天室小项目来巩固串联一下语法。 实现的功能:公聊,私聊,修改用户名 只用到了四个类: m...
    99+
    2024-04-02
  • C语言实现通讯录的示例代码
    目录一、Contact.h文件二、Contact.c文件三、test.c文件一、Contact.h文件 包含函数的声明 #pragma once #define _CRT_SECUR...
    99+
    2022-11-13
    C语言实现通讯录 C语言 通讯录
  • springboot整合腾讯云短信开箱即用的示例代码
    引入腾讯云依赖 <!--腾讯云核心API--> <dependency> <groupId>com.tencentcloudapi&l...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作