学习记录:springboot + websocket + spring-messaging实现服务器向浏览器广播式通信

2 篇文章 0 订阅
1 篇文章 0 订阅

http协议很好地解决了客户端向服务器通信的问题,虽然已经满足了大部分需求,但是难免会有服务器需要向客户端通信的情况,一般的解决方式就有ajax轮询、长轮询、socket。

ajax轮询就是定时使用ajax访问服务器,询问是否有新的消息。

长轮询则是访问服务器后,如果没有新消息,则服务器不做响应,直到请求超时或者有新消息,客户端再次发起请求。

这两种方式都会增加服务器压力,而且感觉有点笨。最好的方式就是使用socket进行长连接,双向通信。


参考了一些网上的博客,但是总是存在一些问题,所以自己整理了一下代码。文中不会对一些概念和术语或者技术做过多解释,这些东西网上很多,而且都比我懂,我只放出源代码,抛砖引玉,让大家少掉坑。

目录结构


红圈内是比较重要的文件,本文也只列出比较重要的文件,源代码我会在末尾给出。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.web.socket</groupId>
    <artifactId>websocket</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>websocket Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <parent>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>2.0.0.RELEASE</version>  
    </parent>  
    <properties>  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
        <java.version>1.8</java.version>  
    </properties> 
    <dependencies>
         <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-messaging</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency> 
        <dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-websocket</artifactId>  
       </dependency> 
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>javax.servlet-api</artifactId>  
            <scope>provided</scope>  
        </dependency> 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>websocket</finalName>
    </build>
</project>

WebSocketConfig.java

这里继承的类过时了,但是水平有限,一直不知道应该怎么替换,有大佬知道的指点指点

package com.web.socket.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

/**
 * @title websocket配置
 * @author yc 2018年5月21日
 */
@Configuration
//表示开启使用STOMP协议来传输基于代理的消息,Broker就是代理的意思。
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
	/**
	 * @title 用来配置消息代理,由于我们是实现推送功能,这里的消息代理是/topic
	 * @author yc 2018年5月21日
	 */
	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.enableSimpleBroker(AppConfig.BROKER);
	}
	/**
	 * @title 表示注册STOMP协议的节点,并指定映射的URL。
	 * @author yc 2018年5月21日
	 */
	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		//这一行代码用来注册STOMP协议节点,同时指定使用SockJS协议。 
		registry.addEndpoint(AppConfig.ENDPOINT).withSockJS();
	}
}

AppConfig.java

package com.web.socket.config;

/**
 * @title 全局参数
 * @author yc 2018年5月23日
 */
public class AppConfig {
	/**
	 * 被订阅的频道
	 */
	public static final String SUBSCRIBE = "/topic/message";
	/**
	 * stomp节点
	 */
	public static final String ENDPOINT = "/endpointYC";
	/**
	 * 消息代理
	 */
	public static final String BROKER = "/topic";
}

WebSocketController.java

package com.web.socket.controller;


import java.io.IOException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.web.socket.config.AppConfig;
import com.web.socket.entity.RequestMessage;
import com.web.socket.entity.ResponseMessage;

@Controller
public class WsController {
	@Autowired
	private SimpMessagingTemplate simpMessagingTemplate;
	
	/**
	 * @title websocket产生消息,并推送
	 * @author yc 2018年5月23日
	 * @param message
	 * @return
	 */
	@MessageMapping("/ws")//和@RequestMapping类似
        @SendTo(AppConfig.SUBSCRIBE)//当服务器有消息需要推送的时候,会对订阅了@SendTo中路径的浏览器发送消息
        public ResponseMessage say(RequestMessage message) {
            System.out.println(message.getName());
            return new ResponseMessage(message.toString());
        }
	
	/**
	 * @title http请求产生消息,并推送
	 * @author yc 2018年5月23日
	 * @param message
	 * @return
	 * @throws IOException
	 */
	@PostMapping("/http")
	@ResponseBody
	public String send(@RequestBody RequestMessage message) throws IOException {
		System.out.println(message.getName());
		simpMessagingTemplate.convertAndSend(AppConfig.SUBSCRIBE,new ResponseMessage(message.toString()) );
		return "success";
	}
}

ws.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>广播式WebSocket</title>
    <script th:src="@{static/js/sockjs.min.js}"></script>
    <script th:src="@{static/js/stomp.js}"></script>
    <script th:src="@{static/js/jquery-3.3.1.min.js}"></script>
</head>
<body οnlοad="disconnect()">
<noscript><h2 style="color: #e80b0a;">Sorry,浏览器不支持WebSocket</h2></noscript>
<div>
    <div>
        <button id="connect" οnclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" οnclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv">
        <label>名字</label><input type="text" id="name"/>
        <label>内容</label><input type="text" id="content"/>
        <button id="sendName" οnclick="sendName();">发送</button>
        <p id="response"></p>
    </div>
</div>
<script type="text/javascript">
    var stompClient = null;
    /**
     * 设置组件样式
     * @param {Object} connected
     */
    function setConnected(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connected;
        document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
    }
    /**
     * 创建socket连接
     */
    function connect() {
    	//链接SockJS 的endpoint 名称为endpointSang
        var socket = new SockJS('/endpointYC');
        //使用stomp子协议的WebSocket 客户端
        stompClient = Stomp.over(socket);
        //链接Web Socket的服务端。
        stompClient.connect({}, function (frame) {
            setConnected(true);
            //订阅/topic/message频道,并对收到信息进行处理
            stompClient.subscribe('/topic/message', function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            })
        });
    }
    /**
     * 断开连接
     */
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
    }
    /**
     * 向服务器发送消息
     */
    function sendName() {
        var name = $('#name').val();
        var content = $('#content').val();
        stompClient.send("/ws", {}, JSON.stringify({'name': name,'content':content,'date':new Date()}));
    }
    /**
     * 替换文本
     * @param {Object} message 服务器返回数据
     */
    function showResponse(message) {
        $("#response").html(message);
    }
</script>
</body>
</html>

以上就是比较重要的文件,注释都写得比较清楚了。

使用浏览器访http://127.0.0.1/ws就可以测试websocket方式广播。

在有socket连接的情况下,访问http://127.0.0.1/http,并使用post方式请求,就可以在ws页面看到发送的数据了。

后面有时间可能会再研究下点对点的通信方式。

源代码:https://github.com/qing-yan/qing

参考资料:

https://blog.csdn.net/u012702547/article/details/53816326


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值