SpringBoot 集成 webSocket,实现后台向客户端推送消息

图文等内容参考链接 SpringBoot2.0集成WebSocket,实现后台向前端推送信息_Moshow郑锴的博客-CSDN博客_springboot websocket

WebSocket 简介

webSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通信的协议。

webSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在webscoket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

为什么需要 WebSocket?

初次接触 WebSocket 的人,都会问同样的问题:我们已经有了 HTTP 协议,为什么还需要另一个协议?它能带来什么好处?

  • 答案很简单,因为 HTTP 协议有一个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。

浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。

当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。


实现步骤

1.添加maven依赖

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

2.WebSocketConfig

启用WebSocket的支持也是很简单,几句代码搞定

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协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller。在类上添加@ServerEndpoint("/websocket") 和 @Component 注解启用

然后在里面实现 @OnOpen, @onClose, @onMessage 等方法

import lombok.extern.slf4j.Slf4j;
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.concurrent.CopyOnWriteArraySet;

@Slf4j
@ServerEndpoint("/websocket/{sid}")
@Component
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中
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
        	 sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        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();
    }
	/**
	 * 实现服务器主动推送,这里可能会出现并发报错,在方法上加 synchronized 就可以了
	 */
    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--;
    }
}

4.消息推送

至于推送新信息,可以在自己的Controller写个方法调用WebSocketServer.sendInfo();

import com.gasy.mmo.web.ws.service.WebSocketServer;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


@RestController
@RequestMapping("ws")
public class WsController {

    /**
     * @param sid 客户端 sid
     */
    @GetMapping("msg/{sid}")
    public String wsMsg(@PathVariable("sid") String sid) {
        try {
            String msg = "*** 推送的消息内容!***";
            WebSocketServer.sendInfo(msg, sid); // 向连接为 {sid} 的客户端窗口发送消息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success !!!";
    }

}

5. web页面发起socket请求

然后在页面用js代码调用socket,当然,太古老的浏览器是不行的,一般新的浏览器或者谷歌浏览器是没问题的。还有一点,记得协议是ws的

/* WebSocket 连接 */
var wssocket;
function wsConnect() {
    // web模块端口:8082
    var WsUrl = "ws://localhost:8082/websocket/notice";    // notice 即为接口参数 sid
    if (typeof (WebSocket) == "undefined") {
        console.log("浏览器不支持WebSocket")
        return;
    }
    wssocket = new WebSocket(WsUrl);
    wssocket.onopen = function() {
        console.log("ws 已打开");
    };
    wssocket.onmessage = function(msg) {
        console.log('收到消息:' + msg.data);
    };
    wssocket.onclose = function() {
        console.log("ws 已关闭");
    };
    wssocket.onerror = function() {
        alert("ws 发生了错误");
    }
}

完毕

例子,我在vue.js中的发起请求的写法

<script>
  export default {
    name: "**",
    data() {
      return {
        socket: null,
        
        // 代码片段

      }
    },
    mounted() {
      // 代码片段
      /**
       * 页面发起socket 请求
       * @type {WebSocket}
       */
      this.socket = new WebSocket("ws://localhost:8080/websocket/test");
      this.socket.onopen = function() {
        console.log("Socket 已打开");
      };
      this.socket.onmessage = function(msg) {
        console.log('收到消息:' + msg.data);
      };
      this.socket.onclose = function() {
        console.log("this.socket已关闭");
      };
      this.socket.onerror = function() {
        alert("Socket发生了错误");
      }
    },
    methods: {
      // 代码片段
      // http请求数据如下:
      submit: function () {    
        this.axios
          .get('url', {
          params:
            {
              // 向服务器传数据
            }
          })
          .then(res => {
            // 获得后台数据
            this.info = res.data;   /* 使用 response.data 读取 JSON 数据 */
            console.log(res);
          })
          .catch(function (error) {
              console.log(error)
          })
      },

    }

  }

</script>

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值