uni-app关于WebSocket与Netty后端的记录

7 篇文章 0 订阅
1 篇文章 0 订阅

所使用到API的基本介绍

作者对于Netty的学习也是刚刚入门,前后端联调花了两三天时间,于是赶快记录下来

Uni-App WebSocket API

更多API参考Uni-App官网

  • uni.connectSocket(OBJECT)
    创建一个 WebSocket 连接
参数名类型必填说明
urlString服务器接口地址
successFunction接口调用成功的回调函数
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)
// 使用次形式会返回一个 SocketTask 类型的对象
uni.connectSocket({
    url: 'ws://127.0.0.1/ws',	//在这里我是用wss连接不上后端
    success(data) {
		console.log("websocket连接成功");
	}
});
  • SocketTask.onOpen(CALLBACK)
    监听 WebSocket 连接打开事件
this.socketTask.onOpen((res) => {
	console.log("WebSocket连接正常打开中...");
})
  • SocketTask.onMessage(CALLBACK)
    监听 WebSocket 接受到服务器的消息事件
// 只有连接正常打开中 ,才能正常收到消息
this.socketTask.onMessage((res) => {
	console.log("收到服务器内容:" + res.data);	// data 服务器返回的消息
});
  • SocketTask.send(OBJECT)
    通过 WebSocket 连接发送数据
this.socketTask.send({
	data: "Hello",	// 发送的数据
	async success() {	// 消息发送成功的回调
		console.log("消息发送成功");
	},
});

Nety API

更多API结合翻译软件查看Netty 4.0官网
对于可能错误的阐述欢迎在评论区指正

  • EventLoopGroup
    简单的来说,这个对象的作用就是对传入到服务器的连接进行管理

  • ServerBootstrap
    服务端的启动器,启动或者说使用Netty的必须类.至于在客服端会使用到Bootstrap本案例不会被用到

  • NioServerSocketChannel
    使用的传输方式为NIO

  • ChannelInitializer
    初始化类,实现该类可以在其initChannel方法中做出各种配置,不可避免的会在这里面添加自定义的handler

  • SimpleChannelInboundHandler
    自定义handler可以继承它,可以重写它的方法实现对连接的监控以及对缓冲区内容的读写,更多方法在代码中以注释方法解释

案例简单概述

一个输入框,一个按钮,一个text标签
在输入框中输入,通过按钮提交到后端Netty服务器,服务器接收到消息将数据重新写回客户端(即小程序),并在text标签中显示
在这里插入图片描述

代码实现

服务器端代码

WsServer 服务器

package com.demo02_webAndServer;

// 为节约篇幅,导包部分省略,全部倒入关于netty包就OK了
import io.netty.*;

/**
 * 服务器
 */
public class WsServer {

    // 将这个类设置为单利模式,此处没有使用Spring所以只能手动实现单例.
    private static final WsServer instance = new WsServer();

    public static WsServer getInstance(){
        return instance;
    }

    private EventLoopGroup main;
    private EventLoopGroup work;
    private ServerBootstrap serverBootstrap;
    private ChannelFuture future;

    public void start() throws InterruptedException {

        final WsServerHandler wsServerHandler = new WsServerHandler();
        main = new NioEventLoopGroup();
        work = new NioEventLoopGroup();
        try {
            serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(main,work)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 配置handler
                            pipeline.addLast(new HttpServerCodec());    // websocket 基于 http 协议,需要http编码和解码工具
                            pipeline.addLast(new ChunkedWriteHandler());    // 对于大数据流的支持
                            pipeline.addLast(new HttpObjectAggregator(1024 * 64));   // 对于http的小心进行聚合,聚合成FullHttpRequest,几乎所有的netty都需要次handler
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));	// 路由,只有跟ws的请求才会被处理
                            pipeline.addLast(wsServerHandler);	// wsServerHandler自定义的一个handler
                        }
                    });

            System.err.println( "Netty WebSocket server 成功启动");
            future = serverBootstrap.bind(8088).sync(); // 监听到指定端口
            future.channel().closeFuture().sync();
        }finally {
            main.shutdownGracefully().sync();	// 优雅关闭
            work.shutdownGracefully().sync();
        }

    }

}

WsServerHandler 引导服务器

package com.demo02_webAndServer;

import io.netty.*;

@ChannelHandler.Sharable
public class WsServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    // 定义channel集合,管理channel,传入全局事件执行器
    public static ChannelGroup usersGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 将新连接的客户端channel 放入 usersGroup 中管理
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有新的连接...");
        usersGroup.add(ctx.channel());
    }

    // 处理器移除时,移除usersGroup中的channel
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.err.println("客户端被移除,channelID为 : " + ctx.channel().id().asLongText() + ",short : " +ctx.channel().id().asShortText());
        usersGroup.remove(ctx.channel());
    }

    // 发生异常时将channel移除
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
        System.out.println("发生了异常..");
        usersGroup.remove(ctx.channel());
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到来自客户端的消息(" + ctx.channel().id().asShortText() + ") : " + msg.text() );
        String s = msg.text();
        ctx.channel().writeAndFlush(new TextWebSocketFrame("ok" + s)); // 在收到的消息前加一个ok并写回客户端
    }
}

由于这是一个普通的Java项目,所以我们需要创建一个启动类

package com.demo02_webAndServer;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        WsServer.getInstance().start();
    }
}

就这样,Netty服务端就可以启动了.

前端小程序代码


<template>
	<view class="websockets">
		<input type="text" class="message_text" v-model="message_itext"  />
		<button type="primary" @tap="clickRequest">点击发送请求</button>
		<text>{{response}}</text>
	</view>
</template>
 
<script>
	export default {
		onLoad() {
			// 进入这个页面的时候创建websocket连接,整个页面随时使用
			this.connectSocketInit();
		},
		data() {
			return {
				socketTask: null,
				// 确保websocket是打开状态,初始未打开
				is_open_socket: false,
				message_itext : "",
				response : ""
			}
		},
		// 关闭websocket,必须在实例销毁之前关闭,否则会是underfined错误
		beforeDestroy() {
			this.closeSocket();
		},
		methods: {
			// 创建websocket连接方法
			connectSocketInit() {
				// 创建一个this.socketTask对象,发送、接收、关闭socket都由这个对象操作
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的
					url: "ws://172.17.186.27:8088/ws",	// 此处地址最好不要天127.0.0.1,不然手机调试的时候忘记改就会出错
					success(data) {
						console.log("websocket连接成功");
					}
				});
 
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收,否则会失败
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...");
					this.is_open_socket = true;
				})
				// 注:只有连接正常打开中 ,才能正常收到消息
				this.socketTask.onMessage((res) => {
					console.log("收到服务器内容:" + res.data);
					this.response = res.data
				});
				// 这里仅是事件监听,如果socket关闭了会执行
				this.socketTask.onClose(() => {
					console.log("已经被关闭了")
				})
				
			},
			// 关闭websocket,离开这个页面的时候执行关闭
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.is_open_socket = false;
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})
			},
			clickRequest() {
				if (this.is_open_socket) {
					// 发送消息,同时返回一组数据
					this.socketTask.send({
						data: this.message_itext,
						async success() {	// 同步接收
							console.log("消息发送成功");
						},
					});
				}
			}
		}
	}
</script>

<style>
	.message_text{
		border: #007AFF 2upx solid;
		margin: 5upx;
	}
</style>

好了,小程序端的代码也写完了

总结

代码都有了,还不快去运行一下^-^

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值