springboot2学习-webflux与websocke

         websocket可以实现双向通信,客户端可以给服务端发送消息,服务端也可以给客户端发送消息,是一种通信技术,使用websocket我们可以很容易的实现简单的聊天系统。之前的博客也写过websocket的demo,参考:https://blog.csdn.net/j903829182/article/details/78342941,不了解的可以看看。

        这里是学习springboot2里面的webflux中与websocket的整合,参考:http://gitbook.cn/gitchat/column/5acda6f6d7966c5ae1086f2b/topic/5acdaa79d7966c5ae1087094

         1,首先创建一个spring boot项目,pom代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.jack</groupId>
	<artifactId>webflux_websocket</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>webflux_websocket</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</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.boot</groupId>
			<artifactId>spring-boot-starter-webflux</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>io.projectreactor</groupId>
			<artifactId>reactor-test</artifactId>
			<scope>test</scope>
		</dependency>

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

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

2,项目结构如下:



3,编写websocket的服务端,代码如下:

package com.jack.webflux_websocket.handler;

import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * create by jack 2018/6/2
 * websocket 处理类
 */
@Component
public class EchoHandler implements WebSocketHandler {
    @Override
    public List<String> getSubProtocols() {
        return null;
    }

    /**
     * WebSocketHandler 接口,实现该接口来处理 WebSokcet 消息。
     handle(WebSocketSession session) 方法,接收 WebSocketSession 对象,
     即获取客户端信息、发送消息和接收消息的操作对象。
     receive() 方法,接收消息,使用 map 操作获取的 Flux 中包含的消息持续处理,
     并拼接出返回消息 Flux 对象。
     send() 方法,发送消息。消息为“服务端返回:jack, -> ”开头的。
     * @param webSocketSession
     * @return
     */
    @Override
    public Mono<Void> handle(WebSocketSession webSocketSession) {
        return webSocketSession.send(webSocketSession.receive().
                map(msg -> webSocketSession
                        .textMessage("服务端返回:jack ->" + msg.getPayloadAsText())));
    }
}

实现了websockethandler接口,在handler方法里面处理通信消息。


4,websocket的配置类,路由处理,代码如下:

package com.jack.webflux_websocket.config;

import com.jack.webflux_websocket.handler.EchoHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

/**
 * create by jack 2018/6/2
 * websocket 配置类
 */
@Configuration
public class WebSocketConfiguration {
    @Autowired
    @Bean
    public HandlerMapping webSocketMapping(final EchoHandler echoHandler) {
        /**
         * 使用 map 指定 WebSocket 协议的路由,路由为 ws://localhost:8080/echo
         */
        final Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/echo", echoHandler);

        /**
         * SimpleUrlHandlerMapping 指定了 WebSocket 的路由配置
         */
        final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
        mapping.setUrlMap(map);
        return mapping;
    }

    /**
     * WebSocketHandlerAdapter 负责将 EchoHandler 处理类适配到 WebFlux 容器中
     * @return
     */
    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}

5,使用java的websocket客户端连接服务的代码如下:

package com.jack.webflux_websocket.client;

import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import org.springframework.web.reactive.socket.client.WebSocketClient;
import reactor.core.publisher.Flux;

import java.net.URI;
import java.time.Duration;

/**
 * create by jack 2018/6/2
 * WebSocket 客户端去调用 WebSokcet 协议
 */
public class WSClient {
    public static void main(final String[] args) {
        /**
         * ReactorNettyWebSocketClient 是 WebFlux 默认 Reactor Netty 库提供的 WebSocketClient 实现。
         execute 方法,与 ws://localhost:8080/echo 建立 WebSokcet 协议连接。
         execute 需要传入 WebSocketHandler 的对象,用来处理消息,这里的实现和前面的 EchoHandler 类似。
         通过 WebSocketSession 的 send 方法来发送字符串“你好”到服务器端,然后通过 receive 方法来等待服务器端的响应并输出。
         */
        final WebSocketClient client = new ReactorNettyWebSocketClient();
        client.execute(URI.create("ws://localhost:8080/echo"), session ->
                session.send(Flux.just(session.textMessage("你好")))
                        .thenMany(session.receive().take(1).map(WebSocketMessage::getPayloadAsText))
                        .doOnNext(System.out::println)
                        .then())
                .block(Duration.ofMillis(5000));
    }
}

测试:

1)先启动websocket服务端

2,运行websocket客户端程序

    客户端的日志如下:

10:48:01.025 [reactor-http-nio-4] DEBUG reactor.ipc.netty.channel.ChannelOperations - [HttpClient] [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] handler is being applied: HttpClientHandler{startURI=ws://localhost:8080/echo, method=GET, handler=reactor.ipc.netty.http.client.HttpClient$$Lambda$25/1556995360@4262e84}
10:48:01.034 [reactor-http-nio-4] DEBUG reactor.ipc.netty.ReactorNetty - Added encoder [reactor.left.httpAggregator] at the beginning of the user pipeline, full pipeline: [reactor.left.loggingHandler, reactor.left.httpCodec, reactor.left.httpAggregator, reactor.right.reactiveBridge, DefaultChannelPipeline$TailContext#0]
10:48:01.044 [reactor-http-nio-4] DEBUG io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker13 - WebSocket version 13 client handshake key: r0NYLiMm4fMoXTS1aNb2hQ==, expected response: VO75O0zi8fYDbg8BKPAL+ye33Jk=
10:48:01.048 [reactor-http-nio-4] DEBUG reactor.ipc.netty.channel.ChannelOperationsHandler - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] Writing object DefaultFullHttpRequest(decodeResult: success, version: HTTP/1.1, content: UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf(ridx: 0, widx: 0, cap: 0))
GET /echo HTTP/1.1
upgrade: websocket
connection: upgrade
sec-websocket-key: r0NYLiMm4fMoXTS1aNb2hQ==
host: localhost:8080
sec-websocket-origin: http://localhost:8080
sec-websocket-version: 13
user-agent: ReactorNetty/0.7.7.RELEASE
accept: */*
10:48:01.057 [reactor-http-nio-4] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 4096
10:48:01.057 [reactor-http-nio-4] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxSharedCapacityFactor: 2
10:48:01.058 [reactor-http-nio-4] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.linkCapacity: 16
10:48:01.058 [reactor-http-nio-4] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
10:48:01.065 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] WRITE: 255B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 47 45 54 20 2f 65 63 68 6f 20 48 54 54 50 2f 31 |GET /echo HTTP/1|
|00000010| 2e 31 0d 0a 75 70 67 72 61 64 65 3a 20 77 65 62 |.1..upgrade: web|
|00000020| 73 6f 63 6b 65 74 0d 0a 63 6f 6e 6e 65 63 74 69 |socket..connecti|
|00000030| 6f 6e 3a 20 75 70 67 72 61 64 65 0d 0a 73 65 63 |on: upgrade..sec|
|00000040| 2d 77 65 62 73 6f 63 6b 65 74 2d 6b 65 79 3a 20 |-websocket-key: |
|00000050| 72 30 4e 59 4c 69 4d 6d 34 66 4d 6f 58 54 53 31 |r0NYLiMm4fMoXTS1|
|00000060| 61 4e 62 32 68 51 3d 3d 0d 0a 68 6f 73 74 3a 20 |aNb2hQ==..host: |
|00000070| 6c 6f 63 61 6c 68 6f 73 74 3a 38 30 38 30 0d 0a |localhost:8080..|
|00000080| 73 65 63 2d 77 65 62 73 6f 63 6b 65 74 2d 6f 72 |sec-websocket-or|
|00000090| 69 67 69 6e 3a 20 68 74 74 70 3a 2f 2f 6c 6f 63 |igin: http://loc|
|000000a0| 61 6c 68 6f 73 74 3a 38 30 38 30 0d 0a 73 65 63 |alhost:8080..sec|
|000000b0| 2d 77 65 62 73 6f 63 6b 65 74 2d 76 65 72 73 69 |-websocket-versi|
|000000c0| 6f 6e 3a 20 31 33 0d 0a 75 73 65 72 2d 61 67 65 |on: 13..user-age|
|000000d0| 6e 74 3a 20 52 65 61 63 74 6f 72 4e 65 74 74 79 |nt: ReactorNetty|
|000000e0| 2f 30 2e 37 2e 37 2e 52 45 4c 45 41 53 45 0d 0a |/0.7.7.RELEASE..|
|000000f0| 61 63 63 65 70 74 3a 20 2a 2f 2a 0d 0a 0d 0a    |accept: */*.... |
+--------+-------------------------------------------------+----------------+
10:48:01.066 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] FLUSH
10:48:01.076 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] READ: 129B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 48 54 54 50 2f 31 2e 31 20 31 30 31 20 53 77 69 |HTTP/1.1 101 Swi|
|00000010| 74 63 68 69 6e 67 20 50 72 6f 74 6f 63 6f 6c 73 |tching Protocols|
|00000020| 0d 0a 75 70 67 72 61 64 65 3a 20 77 65 62 73 6f |..upgrade: webso|
|00000030| 63 6b 65 74 0d 0a 63 6f 6e 6e 65 63 74 69 6f 6e |cket..connection|
|00000040| 3a 20 75 70 67 72 61 64 65 0d 0a 73 65 63 2d 77 |: upgrade..sec-w|
|00000050| 65 62 73 6f 63 6b 65 74 2d 61 63 63 65 70 74 3a |ebsocket-accept:|
|00000060| 20 56 4f 37 35 4f 30 7a 69 38 66 59 44 62 67 38 | VO75O0zi8fYDbg8|
|00000070| 42 4b 50 41 4c 2b 79 65 33 33 4a 6b 3d 0d 0a 0d |BKPAL+ye33Jk=...|
|00000080| 0a                                              |.               |
+--------+-------------------------------------------------+----------------+
10:48:01.085 [reactor-http-nio-4] DEBUG org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient - Handshake response: ws://localhost:8080/echo, {upgrade=[websocket], connection=[upgrade], sec-websocket-accept=[VO75O0zi8fYDbg8BKPAL+ye33Jk=], content-length=[0]}
10:48:01.099 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] USER_EVENT: reactor.ipc.netty.NettyPipeline$SendOptionsChangeEvent@423259bb
10:48:01.100 [reactor-http-nio-4] DEBUG reactor.ipc.netty.channel.ChannelOperationsHandler - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] New sending options
10:48:01.102 [reactor-http-nio-4] DEBUG reactor.ipc.netty.ReactorNetty - Added decoder [WebSocketFrameAggregator] at the end of the user pipeline, full pipeline: [reactor.left.loggingHandler, reactor.left.httpCodec, ws-decoder, ws-encoder, WebSocketFrameAggregator, reactor.right.reactiveBridge, DefaultChannelPipeline$TailContext#0]
10:48:01.108 [reactor-http-nio-4] DEBUG reactor.ipc.netty.channel.ChannelOperationsHandler - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] Writing object 
10:48:01.110 [reactor-http-nio-4] DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder - Encoding WebSocket Frame opCode=1 length=6
10:48:01.111 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] WRITE: 12B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 81 86 05 a4 81 3f e1 19 21 da a0 19             |.....?..!...    |
+--------+-------------------------------------------------+----------------+
10:48:01.112 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] FLUSH
10:48:01.115 [reactor-http-nio-4] DEBUG reactor.ipc.netty.channel.FluxReceive - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] Subscribing inbound receiver [pending: 0, cancelled:false, inboundDone: false]
10:48:01.116 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] READ COMPLETE
10:48:01.116 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] READ: 33B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 81 1f e6 9c 8d e5 8a a1 e7 ab af e8 bf 94 e5 9b |................|
|00000010| 9e ef bc 9a 6a 61 63 6b 20 2d 3e e4 bd a0 e5 a5 |....jack ->.....|
|00000020| bd                                              |.               |
+--------+-------------------------------------------------+----------------+
10:48:01.117 [reactor-http-nio-4] DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame opCode=1
10:48:01.117 [reactor-http-nio-4] DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame length=31
服务端返回:jack ->你好
10:48:01.119 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClientOperations - Cancelling Websocket inbound. Closing Websocket
10:48:01.119 [reactor-http-nio-4] DEBUG reactor.ipc.netty.channel.ChannelOperationsHandler - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] Writing object CloseWebSocketFrame(data: UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf(ridx: 0, widx: 0, cap: 0))
10:48:01.119 [reactor-http-nio-4] DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder - Encoding WebSocket Frame opCode=8 length=0
10:48:01.120 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] WRITE: 6B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 88 80 3d 61 fd 94                               |..=a..          |
+--------+-------------------------------------------------+----------------+
10:48:01.120 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClientOperations - Handler terminated. Closing Websocket
10:48:01.120 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] READ COMPLETE
10:48:01.120 [reactor-http-nio-4] DEBUG reactor.ipc.netty.http.client.HttpClient - [id: 0x9f5115f6, L:/127.0.0.1:58826 - R:localhost/127.0.0.1:8080] FLUSH

Process finished with exit code 0

通过日志可以看出,websocket进行通信的过程,和获取websocket服务端的消息。


6,使用浏览器页面作为websocket客户端

1)在resource目录下面创建templates目录,在templates目录下创建websocket-client.html页面,页面代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>websocket-client</title>
</head>
<body>
<div class="chat"></div>
</body>
<script>
    var clientWebSocket = new WebSocket("ws://localhost:8080/echo");

    clientWebSocket.onopen = function () {
        console.log("clientWebSocket.onopen", clientWebSocket);
        console.log("clientWebSocket.readyState", "websocketstatus");
        clientWebSocket.send("你好!");
    }

    clientWebSocket.onclose = function (error) {
        console.log("clientWebSocket.onclose", clientWebSocket, error);
        events("聊天会话关闭!");
    }

    clientWebSocket.onmessage=function (msg) {
        console.log(msg);
        document.querySelector(".chat").innerHTML += msg.data + "<br>";
    }

    function events(responseEvent) {
        document.querySelector(".chat").innerHTML += responseEvent + "<br>";
    }
</script>
</html>

2)编写一个控制器,返回页面,代码如下:

package com.jack.webflux_websocket.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * create by jack 2018/6/2
 */
@Controller
public class WebsocketClientController {
    @RequestMapping(value = "/client", method = RequestMethod.GET)
    public String websocketClient() {
        return "websocket-client";
    }
}

测试:

1)启动websocket服务

2)通过浏览器访问http://localhost:8080/client,效果如下:


      

         总结:这里简单的实现了webflux和websocket的整合,真正的使用好这websocket还有很多工作需要做,需要根据需要做很多的工作。使用weblux实现了websocket的异步通信,底层用到了reactor技术。


源码地址:https://github.com/wj903829182/springcloud5/tree/master/webflux_websocket

欢迎加群:331227121一起学习交流



  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值