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

后台:spring boot;前台:angularjs

后台建立服务

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

1.引入websocket依赖

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

<dependencies>
  <!--webSocket-->
  <dependency>
    <groupId>org.spring work.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
  </dependency>
  
  <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>webjars-locator-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>sockjs-client</artifactId>
      <version>1.0.2</version>
    </dependency>
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>stomp-websocket</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap</artifactId>
      <version>3.3.7</version>
    </dependency>
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>3.1.0</version>
    </dependency>
</dependencies>

2.配置类

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

public class WebSocketConfig {}

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

package com.mengyunzhi.SpringMvcStudy.config;

import org.spring work.context.annotation.Configuration;
import org.spring work.messaging.simp.config.MessageBrokerRegistry;
import org.spring work.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.spring work.web.socket.config.annotation.StompEndpointRegistry;
import org.spring work.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.客户端界面

<!DOCTYPE html>
<html>
<head>
  < >Hello WebSocket</ >
  <  href=\"/webjars/bootstrap/css/bootstrap.min.css\" rel=\"external nofollow\" rel=\"stylesheet\">
  <  href=\"/main.css\" rel=\"external nofollow\" rel=\"stylesheet\">
  <  src=\"/webjars/jquery/jquery.min.js\"></ >
  <  src=\"/webjars/sockjs-client/sockjs.min.js\"></ >
  <  src=\"/webjars/stomp-websocket/stomp.min.js\"></ >
  <  src=\"/app.js\"></ >
</head>
<body>
<no ><h2 style=\"color: #ff0000\">Seems your browser doesn\'t support  ! Websocket relies on   being
  enabled. Please enable
    and reload this page!</h2></no >
<div id=\"main-content\" class=\"container\">
  <div class=\"row\">
    <div class=\"col-md-6\">
      <form class=\"form-inline\">
        <div class=\"form-group\">
          <label for=\"connect\">WebSocket connection:</label>
          <button id=\"connect\" class=\"btn btn-default\" type=\"submit\">Connect</button>
          <button id=\"disconnect\" class=\"btn btn-default\" type=\"submit\" disabled=\"disabled\">Disconnect
          </button>
        </div>
      </form>
    </div>
    <div class=\"col-md-6\">
      <form class=\"form-inline\">
        <div class=\"form-group\">
          <label for=\"name\">What is your name?</label>
          <input type=\"text\" id=\"name\" class=\"form-control\" placeholder=\"Your name here...\">
        </div>
        <button id=\"send\" class=\"btn btn-default\" type=\"submit\">Send</button>
      </form>
    </div>
  </div>
  <div class=\"row\">
    <div class=\"col-md-12\">
      <table id=\"conversation\" class=\"table table-striped\">
        <thead>
        <tr>
          <th>Greetings</th>
        </tr>
        </thead>
        <tbody id=\"greetings\">
        </tbody>
      </table>
    </div>
  </div>
</div>
</body>
</html>

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

<  src=\"/webjars/sockjs-client/sockjs.min.js\"></ >
<  src=\"/webjars/stomp-websocket/stomp.min.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 ( ) {
    setConnected(true);
    console.log(\'Connected: \' +  );
    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(\"<tr><td>\" + message + \"</td></tr>\");
}

$(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/messaging-stomp-websocket/

https://docs.spring.io/spring-boot/docs/1.5.17.RELEASE/reference/htmlsingle/#boot-features-websockets

https://docs.spring.io/spring/docs/4.3.20.RELEASE/spring- work-reference/htmlsingle/#websocket

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

收藏 打印