资讯专栏INFORMATION COLUMN

使用spring的websocket创建通信服务

wuyangnju / 2371人阅读

摘要:基于通信,也有自己的通信服务,这次就介绍如何在项目中使用进行通信交互。接着设置一个请求路由前缀,它绑定了这个后面会用到注解,表示以为前缀的消息,会发送到服务器端。最后实现了方法,用来注册端点来建立服务器。

基于socket通信,spring也有自己的socket通信服务:websocket,这次就介绍如何在spring项目中使用websocket进行通信交互。

后台:spring boot;前台:angularjs

后台建立服务

首先我们先建立起后台的服务,以实现进行socket连接。

1.引入websocket依赖

建立好一个maven项目之后,我们需要在xml中引入websocket的相关 依赖:


    
    
        org.springframework.boot
        spring-boot-starter-websocket
    
    
    
            org.webjars
            webjars-locator-core
        
        
            org.webjars
            sockjs-client
            1.0.2
        
        
            org.webjars
            stomp-websocket
            2.3.3
        
        
            org.webjars
            bootstrap
            3.3.7
        
        
            org.webjars
            jquery
            3.1.0
        
2.配置类

引入依赖后,就需要我们进行配置类的编写:

public class WebSocketConfig {}

这个类需要实现一个接口,来帮助我们进行socket的连接,并接受发送过来的消息。比如下面这样:

package com.mengyunzhi.SpringMvcStudy.config;

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

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/server");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //注册STOMP协议节点,同时指定使用SockJS协议
        registry
            .addEndpoint("/websocket-server")
            .setAllowedOrigins("*")
            .withSockJS();
    }
}

通常的配置我就不在这里解释了,值得一提的是,我们使用了@EnableWebSocketMessageBroker这个注解,从字面上我们不难猜出,它表示支持websocket提供的消息代理。

然后我们实现configureMessageBroker()方法,来配置消息代理。在这个方法中,我们先调用enableSimpleBroker()来创建一个基于内存的消息代理,他表示以/topic为前缀的消息将发送回客户端。接着设置一个请求路由前缀,它绑定了@MessageMapping(这个后面会用到)注解,表示以/server为前缀的消息,会发送到服务器端。

最后实现了registerStompEndpoints()方法,用来注册/websocket-server端点来建立服务器。

3.控制器

这时我们要建立一个供前台访问的接口来发送消息。

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
    Thread.sleep(1000); // simulated delay
    return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}

其中@MessageMapping注解就是我们前面提到的,前台会将消息发送到/server/hello这里。

然后还有一个@SendTo注解,它表示服务器返回给前台的消息,会发送到/topic/greeting这里。

前台客户端

服务器部分建立好后,接着我们就要去建立客户端部分

1.客户端界面



    Hello WebSocket
    
    
    
    
    
    



Greetings

这部分没什么说的,主要就是其中引的连个js文件:


这两个文件帮助我们利用sockjsstomp实现客户端。

创建逻辑
var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    var socket = new SockJS("/websocket-server");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log("Connected: " + frame);
        stompClient.subscribe("/topic/greetings", function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    stompClient.send("/server/hello", {}, JSON.stringify({"name": $("#name").val()}));
}

function showGreeting(message) {
    $("#greetings").append("" + message + "");
}

$(function () {
    $("form").on("submit", function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() { connect(); });
    $( "#disconnect" ).click(function() { disconnect(); });
    $( "#send" ).click(function() { sendName(); });
});

这个文件主要注意connect()sendName()这两个方法。

最后实现的效果如下:

官方文档:
https://spring.io/guides/gs/m...
https://docs.spring.io/spring...
https://docs.spring.io/spring...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72122.html

相关文章

  • 分布式WebSocket集群解决方案

    摘要:广播这是最简单的集群通讯解决方案。实现方法在治理中心监听集群服务事件,并及时更新哈希环。 问题起因 最近做项目时遇到了需要多用户之间通信的问题,涉及到了WebSocket握手请求,以及集群中WebSocket Session共享的问题。 期间我经过了几天的研究,总结出了几个实现分布式WebSocket集群的办法,从zuul到spring cloud gateway的不同尝试,总结出了...

    nanchen2251 评论0 收藏0
  • Spring整合Netty、WebSocket互联网聊天系统

    摘要:当用户注销或退出时,释放连接,清空对象中的登录状态。聊天管理模块系统的核心模块,这部分主要使用框架实现,功能包括信息文件的单条和多条发送,也支持表情发送。描述读取完连接的消息后,对消息进行处理。 0.前言 最近一段时间在学习Netty网络框架,又趁着计算机网络的课程设计,决定以Netty为核心,以WebSocket为应用层通信协议做一个互联网聊天系统,整体而言就像微信网页版一样,但考虑...

    My_Oh_My 评论0 收藏0
  • 全栈开发——动手打造属于自己直播间(Vue+SpringBoot+Nginx)

    摘要:经过琢磨,其实是要考虑安全性的。具体在以下几个方面跨域连接协议升级前握手拦截器消息信道拦截器对于跨域问题,我们可以通过方法来设置可连接的域名,防止跨站连接。 前言 大学的学习时光临近尾声,感叹时光匆匆,三年一晃而过。同学们都忙着找工作,我也在这里抛一份简历吧,欢迎各位老板和猎手诚邀。我们进入正题。直播行业是当前火热的行业,谁都想从中分得一杯羹,直播养活了一大批人,一个平台主播粗略估计就...

    e10101 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<