SpringBoot集成WebSocket进行前后端通信

项目场景:

 

SpringBoot集成WebSocket进行前后端通信


实现步骤:

1.引入Maven依赖

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

2.配置WebSocket

创建配置类启用WebSocket支持,用@Configuration和@Bean纳入spring

package com.test.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.核心业务代码

因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller

package com.test.service;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

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 org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * @ ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@Component
@Slf4j
@Service
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {
	//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        this.sid = sid;
        addOnlineCount(); //在线数加1
        try {
            sendMessage("conn_success");
            log.info("有新窗口开始监听:" + sid + ",当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("websocket IO Exception");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
        subOnlineCount(); //在线数减1
        //断开连接情况下,更新主板占用情况为释放
        log.info("释放的sid为:"+sid);
        //这里写你 释放的时候,要处理的业务
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());

    }

    /**
     * 收到客户端消息后调用的方法
     * @ Param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @ Param session
     * @ Param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口" + sid + ",推送内容:" + message);

        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if (sid == null) {
// item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

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

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

4.测试Controller

package com.test.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.test.service.WebSocketServer;

import io.swagger.annotations.Api;

@RestController
@RequestMapping("/test")
@Api(tags = { "测试" })
public class TestController {

    //推送数据接口
    @PostMapping("/socket/push/{sid}")
    public Map pushToWeb(@PathVariable String sid, String message) {
        Map<String,Object> result = new HashMap<>();
        try {
            WebSocketServer.sendInfo(message, sid);
            result.put("code", sid);
            result.put("msg", message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
}

5.测试页面

<!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");
			//指定要连接的服务器地址与端口
			var socketUrl = "ws://127.0.0.1:8080/websocket/localId";
			console.log(socketUrl);
			if (socket != null) {
				socket.close();
				socket = null;
			}
			// 实例化WebSocket对象,建立连接
			socket = new WebSocket(socketUrl);
			//打开事件
			socket.onopen = function() {
				console.log("websocket已打开");
				setMessageInnerHTML("websocket已打开");
			};
			//获得消息事件
			socket.onmessage = function(msg) {
				console.log(msg.data);
				//消息进入后的处理逻辑
				setMessageInnerHTML("服务端回应: "+msg.data);
			};
			//关闭事件
			socket.onclose = function() {
				console.log("websocket已关闭");
				setMessageInnerHTML("websocket已关闭");
			};
			//发生了错误事件
			socket.onerror = function() {
				console.log("websocket发生了错误");
			}
		}
	}
	function sendMessage() {
		if (typeof (WebSocket) == "undefined") {
			console.log("您的浏览器不支持WebSocket");
		} else {
			console.log("您的浏览器支持WebSocket");
			
			var message = $('#text').val();
			socket.send(message);
			
			setMessageInnerHTML(message);
		}
	}
	
	//将消息显示在网页上
	function setMessageInnerHTML(innerHTML) {
		$("#message").append(innerHTML + '<br/>');
	}
	
	//关闭WebSocket连接
	function closeWebSocket() {
		socket.close();
	}
	
	//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
	window.onbeforeunload = function() {
		closeWebSocket();
	}
</script>
<body>
	<div  id="main"  style="width: 1200px;height:800px;"></div>
	Welcome
	<br />
	<input id = "text" value="这是一条测试消息"/>
	<button onclick="sendMessage()">发送消息</button>
	<hr />
	<button onclick="openSocket()">连接socket</button>
	<button onclick="closeWebSocket()">关闭WebSocket连接</button>
	<hr />
	<div id="message"></div>
</body>
</html>

效果截图:

在线测试:

http://www.jsons.cn/websocket/

源码地址:https://download.csdn.net/download/u011974797/87671789

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
SpringBoot集成WebSocket是指在SpringBoot项目中使用WebSocket技术来实现后台向前端推送信息的功能。通过集成WebSocket,可以实现实时的双向通信,使后端能够主动向前端推送消息。 要实现SpringBoot集成WebSocket,首先需要创建一个SpringBoot项目,并引入WebSocket依赖。可以在pom.xml文件中添加以下依赖: ``` <!-- WebSocket dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.7.12</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.7.12</version> </dependency> ``` 然后,需要在SpringBoot的配置类上添加@EnableWebSocket注解,启用WebSocket功能。同时,可以创建一个WebSocket处理器类,用于处理WebSocket连接和消息的处理逻辑。 在启动项目后,可以通过访问http://localhost:8081/demo/toWebSocketDemo/{cid}来跳转到页面,然后就可以和WebSocket进行交互了。通过WebSocket连接,后台可以向前端主动推送消息,实现实时的双向通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot 集成WebSocket详解](https://blog.csdn.net/qq_42402854/article/details/130948270)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛哥是个大帅比

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值