百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

springboot websocket开发(java spring boot websocket)

liuian 2025-07-17 20:39 71 浏览

maven依赖

SpringBoot2.0对WebSocket的支持简直太棒了,直接就有包可以引入

	<dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-websocket</artifactId>  
       </dependency> 

WebSocketConfig

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

/**
 * 开启WebSocket支持
 * @author zhengkai.blog.csdn.net
 */
@Configuration  
public class WebSocketConfig {  
	
    @Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();  
    }  
  
} 

WebSocketServer

package com.softdev.system.demo.config;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;


/**
 * @author zhengkai.blog.csdn.net
 */
@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServer {

    static Log log=LogFactory.get(WebSocketServer.class);
    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if(StringUtils.isNotBlank(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                }else{
                    log.error("请求的userId:"+toUserId+"不在该服务器上");
                    //否则不在这个服务器上,发送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId+",报文:"+message);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线!");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

消息推送

import com.softdev.system.demo.config.WebSocketServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;

/**
 * WebSocketController
 * @author zhengkai.blog.csdn.net
 */
@RestController
public class DemoController {

    @GetMapping("index")
    public ResponseEntity<String> index(){
        return ResponseEntity.ok("请求成功");
    }

    @GetMapping("page")
    public ModelAndView page(){
        return new ModelAndView("websocket");
    }

    @RequestMapping("/push/{toUserId}")
    public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException {
        WebSocketServer.sendInfo(message,toUserId);
        return ResponseEntity.ok("MSG SEND SUCCESS");
    }
}

页面测试调用

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket;
    function openSocket() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl="http://localhost:XXXX/demo/imserver/"+$("#userId").val();
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            console.log(socketUrl);
            if(socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function() {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);
                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            socket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                console.log("websocket发生了错误");
            }
        }
    }
    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            console.log("您的浏览器支持WebSocket");
            console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
            socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
        }
    }
</script>
<body>
<p>【userId】:<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="20"></div>
<p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:<div><a onclick="openSocket()">开启socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div>
</body>

</html>

运行效果

Vue版本的websocket连接

<script>
export default {
    data() {
        return {
            socket:null,
            userId:localStorage.getItem("ms_uuid"),
            toUserId:'2',
            content:'3'
        }
    },
  methods: {
    openSocket() {
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
        //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
        var socketUrl =
          "http://localhost:8081/imserver/" + this.userId;
        socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
        console.log(socketUrl);
        if (this.socket != null) {
          this.socket.close();
          this.socket = null;
        }
        this.socket = new WebSocket(socketUrl);
        //打开事件
        this.socket = new WebSocket(socketUrl);
        //打开事件
        this.socket.onopen = function() {
          console.log("websocket已打开");
          //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        this.socket.onmessage = function(msg) {
          console.log(msg.data);
          //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        this.socket.onclose = function() {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        this.socket.onerror = function() {
          console.log("websocket发生了错误");
        };
      }
    },
    sendMessage() {
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        console.log(
          '{"toUserId":"' +
             this.toUserId +
            '","contentText":"' +
             this.content +
            '"}'
        );
        this.socket.send(
          '{"toUserId":"' +
             this.toUserId +
            '","contentText":"' +
             this.content +
            '"}'
         );
    
    }
}

相关推荐

老桃毛u盘重装系统win7(老桃毛u盘重装系统找不到引导分区)

第一步,你的重装系统以后你U盘没有拔拔掉,它会重复的进入安装系统的界面,只要拔掉U盘就可以解决这个问题。第二个就是硬盘的问题,如果硬盘的问题直接改变一下硬盘模式,就可以解决这个问题,通过这两个方法完全...

u盘修复软件哪个最好免费(u盘修复免费软件有哪些)

恢复U盘数据的软件还是很多的,比如嗨格式数据恢复大师使用就很方便,使用方法如下:1、首先打开电脑浏览器,搜索“嗨格式数据恢复大师”,选择软件主界面中的“快速扫描恢复”模式对磁盘进行扫描。2、当扫描模式...

如何清理c盘缓存文件(怎么清除c盘的缓存)

具体步骤如下:1、首先在电脑桌面找到“计算机”图标(有的可能是我的电脑)双击左键打开。2、在打开的页面中找到“本地磁盘C”,然后右键单击。3、右键单击以后会出现一个菜单,我们在菜单的最底部扎到“属性”...

免费下载最新浏览器(免费下载最新浏览器安装)
  • 免费下载最新浏览器(免费下载最新浏览器安装)
  • 免费下载最新浏览器(免费下载最新浏览器安装)
  • 免费下载最新浏览器(免费下载最新浏览器安装)
  • 免费下载最新浏览器(免费下载最新浏览器安装)
卡巴斯基全方位激活码(卡巴斯基全方位激活码在哪)

当你第一次用的时候能有个半年的免费激活吗码以后你修改系统内部的设置比如重装都会说你您输入的激活码已经超过允许安装的最大次数建议你先免费试用一个月或者用咱们国产的金山毕竟卡巴过分依赖病毒库...

win10最清晰字体(window10怎么调字体清晰度)

首先,在Win10的桌面点击鼠标右键,选择“显示设置”在“显示设置”的界面下方,点击“高级显示设置”在“高级显示设置”的界面中,点击下方的“文本和其他项目大小的调整的高级选项”然后,点击“更改项目的大...

网络上xp是什么梗(xp是什么意思网络)

x是喜欢的意思,p是偏好的意思,原神xp党指的是一直在使用XP系统玩原神,不愿意更新系统的人。

电脑如何升级到win7

Windows7升级到Windows10系统需要使用官方的升级功能完成,以下是具体的操作方法:?1、在微软Windows10网站下载系统版本工具,完成右键以管理员身份打开【MediaCreationT...

手机下载pe启动盘(手机pe启动盘制作工具)

使用手机制作电脑PE启动盘需要以下步骤:1.手机需要支持OTG功能,并插入U盘。2.下载并安装一个名为“Rufus”的应用程序,它可以将U盘制作成可引导的PE启动盘。3.打开Rufus应用程序,...

2025年路由器推荐(2021年值得买的路由器)

水星AX18G这个无线速率是1800Mbps也属于“阉割”版的,跟标准的WiFi6还有一定差距。不过价格便宜,也可以作为WiFi6的尝试产品家里有宽带的话,买个无线路由器,约100元左右就行。每月交宽...

磁盘分区形式(磁盘分区形式MBR与GPT怎么转换)

怎么进行磁盘分区,可以参考以下步骤:步骤1.在“此电脑”上右键点击,选择“管理”,然后在“计算机管理”窗口的左侧列表中选择“磁盘管理”。在Windows10中也可以右键点击开始菜单,直接选择“磁盘...

固态硬盘使用寿命(固态硬盘使用寿命多久)

2012年9月买的联想U410超极本,到目前五年多,使用6300小时左右,电池损耗率只有15%+,固态硬盘升级120GB+原装的500GB机械硬盘,内存升级到16GB(上限了),加上Primocach...

general(general是什么意思)

GENERAL的意思是:1、adj.一般的,普通的;综合的;大体的2、n.一般;将军,上将;常规短语:1、generaldesign总体设计2、generalhospital总医院;综合医...

手机处理器排名最新图(手机处理器排行榜全部)

众所周知,手机端SOC很少在插电模式下运行,因此能耗比在移动端CPU性能中特别重要。本文整理了主流的SOC能耗比情况,给大家购买手机做一个参考。SOC能耗比较高的,包括麒麟810,骁龙625,麒麟65...

pdf版本怎么弄(怎么把word转为pdf)

回答如下:要将PDF文件恢复到以前的版本,您需要执行以下步骤:1.找到保存PDF文件的文件夹或位置。2.在该位置中找到以前的版本,这可能是备份文件、自动保存文件或之前保存的版本。3.如果您没有备...