spring boot 集成WebScoket(端口推送)

spring boot 集成WebScoket(特定端口推送)


参考文章地址:
WebScoket原理: https://www.cnblogs.com/fuqiang88/p/5956363.html
端口消息推送: https://blog.csdn.net/moshowgame/article/details/80275084
Netty的高性能Websocket服务器: https://blog.csdn.net/moshowgame/article/details/83663018

1.什么是WebScoket

在这里插入图片描述
在这里插入图片描述
Http协议的缺陷:通信只能由客户端发起,服务器无法主动向客户端推送信息。使用ajax轮询、long poll浪费资源。

2.代码示例

maven依赖

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

	<!-- 启用Netty https://mvnrepository.com/artifact/org.yeauty/netty-websocket-spring-boot-starter -->
<!--
<dependency>
    <groupId>org.yeauty</groupId>
    <artifactId>netty-websocket-spring-boot-starter</artifactId>
    <version>0.6.5</version>
</dependency>
-->

WebSocketConfig

 	package com.myself.computerThinking.WebScoket;

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


/**
 * 开启WebScoket支持
 */
@Configuration
public class WebScoketConfig {

    /**
     * * 注入对象ServerEndpointExporter,
     *  * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
 

WebSocketServer
因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
直接@ServerEndpoint("/websocket")@Component启用即可,然后在里面实现@OnOpen,@onClose,@onMessage等方法

package com.myself.computerThinking.WebScoket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。
 * 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。
 */
@ServerEndpoint("/websocket/{sid}")
@Component     //此注解千万千万不要忘记,它的主要作用就是将这个监听器纳入到Spring容器中进行管理
public class WebSocketServer {

    static Logger log= LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    //private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    private static ConcurrentHashMap<String, ArrayList<WebSocketServer>> webSocketServers = new ConcurrentHashMap<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //接收sid
    private String sid="";
    /**
     * 建立连接成功的方法
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        ArrayList<WebSocketServer> list=webSocketServers.get(sid);
        if(list==null){
            list = new ArrayList<>();
            webSocketServers.put(sid,list);
        }
        list.add(this);
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketServers.get(this.sid)!=null){
            webSocketServers.get(this.sid).remove(this);
            subOnlineCount();           //在线数减1
            log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
        }

    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     *
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+sid+"的信息:"+message);
            try {
                this.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    
    @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);
        ArrayList<WebSocketServer> webSocketServerList =webSocketServers.get(sid);
        if(webSocketServerList!=null){
            for (WebSocketServer webSocketServer:webSocketServerList){
                webSocketServer.sendMessage(message);
            }
        }
    }

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

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

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

消息推送

package com.myself.computerThinking.WebScoket;

import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.LinkedHashMap;

@Controller
@RequestMapping("/checkcenter")
public class WebSocketController {

    //页面请求
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav=new ModelAndView("/webScoket");
        mav.addObject("cid", cid);
        return mav;
    }
    //推送数据接口
    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public Object pushToWeb(@PathVariable String cid, String message) {
        LinkedHashMap result= new LinkedHashMap();
        try {
            WebSocketServer.sendInfo(message,cid);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("error",cid+"#"+e.getMessage());
            result.put("code",500);
            return result;
        }
        result.put("success",cid);
        result.put("code",200);
        return result;
    }
}

页面发起socket请求

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>接受消息</title>
</head>
<body>

</body>
<script th:inline="javascript">
    var socket;
    var cid=[[${cid}]]
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket("ws://localhost:8080/websocket/"+cid);
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
        //离开页面时,关闭socket
        //jquery1.8中已经被废弃,3.0中已经移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }
</script>
</html>

连接地址:
http://localhost:8083/checkcentersys/checkcenter/socket/20

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Spring Boot可以很容易地集成WebSocket来实现后台向前端推送信息。首先,在你的项目中添加WebSocket的依赖。然后,在controller层加上相应的注解,如@SpringBootApplication和@EnableWebSocket。最后,启动项目并访问指定的URL来与WebSocket进行交互。 具体步骤如下: 1. 添加WebSocket的依赖到你的项目中,可以在pom.xml文件中添加以下代码: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 在controller层,加上@SpringBootApplication和@EnableWebSocket注解,如下所示: ```java @SpringBootApplication @EnableWebSocket public class MywebsocketApplication { public static void main(String[] args) { SpringApplication.run(MywebsocketApplication.class, args); } } ``` 3. 创建一个WebSocket处理器类,可以通过继承自AbstractWebSocketHandler来实现。你可以在这个类中定义处理WebSocket连接、消息发送和接收的逻辑。 4. 在controller中,创建一个处理WebSocket请求的方法,并使用@MessageMapping注解来指定接收消息的路径。在这个方法中,你可以调用WebSocket处理器类的方法来处理消息,并使用WebSocketSession对象来发送消息给前端。 5. 启动你的项目,并访问指定的URL(例如http://localhost:8081/demo/toWebSocketDemo/{cid}),跳转到页面后,就可以与WebSocket进行交互了。 以上就是Spring Boot集成WebSocket的基本步骤。你可以根据具体的需求来进一步扩展和定制WebSocket的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *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_1"}}] [.reference_item style="max-width: 50%"] - *2* [springboot 集成webSocket](https://blog.csdn.net/just_learing/article/details/125899260)[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_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值