netty实现即时通讯,前后端实现Flutter,MUI

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

后端

  1. 创建主副线程组绑定端口号channel及childHandler
  2. 写childHandler的实现,在channel的pipeline 一系列的Handler
  3. 最后加入自己的ChatHandler的实现

代码

public class WSServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup mainGroup = new NioEventLoopGroup();
        NioEventLoopGroup subGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(mainGroup,subGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WSServerInitialzer());
            ChannelFuture future = server.bind(8188).sync();
            future.channel().closeFuture().sync();
        } finally {
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }
    }
}
public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new ChatHandler());
    }
}
public  class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup channels= new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        System.err.println("[channelRead0]:"+text);
        for (Channel channel : channels) {
            channel.writeAndFlush(new TextWebSocketFrame("[channelRead0] server receved msg:"+ LocalDateTime.now()+"is"
            +text
            ));
        }
    }
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//        super.handlerAdded(ctx);
        System.err.println("[handlerAdded]:"+ctx.channel().id());
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        channels.remove(ctx.channel());
        //一个客户端对应一个channel
        System.err.println("[handlerRemoved]:"+ctx.channel().id());
    }


}

Flutter实现移动端

import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    final title = 'WebSocket Demo';
    return new MaterialApp(
      title:title,
      home: new MyHomePage(
        title: title,
        channel: new IOWebSocketChannel.connect('ws://192.168.0.8:8188/ws'),//如果是本地直接使用IP地址而非localhost或127.0.0.1
      ),
    );
  }
}

class MyHomePage extends StatefulWidget{
  final String title;
  final WebSocketChannel channel;

  MyHomePage({Key key,@required this.title,@required this.channel}): super(key: key);
  @override
  _MyHomePageState createState()=> new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>{
  TextEditingController _controller = new TextEditingController();

  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Padding(
        padding: const EdgeInsets.all(20.0),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Form(
              child: new TextFormField(
                controller: _controller,
                decoration: new InputDecoration(labelText: 'Send a message'),
              ),
            ),
            new StreamBuilder(
                stream: widget.channel.stream,
                builder: (context, snapshot){
                return new Padding(
                padding: const EdgeInsets.symmetric(vertical: 24.0),
                child: new Text(snapshot.hasData?'${snapshot.data}':''),
              );
            }),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: new Icon(Icons.send),
      ),
    );
  }
  void _sendMessage(){
    if (_controller.text.isNotEmpty){
      widget.channel.sink.add(_controller.text);
      print("send message completed");
    }
  }
  
  @override
  void dispose(){
    widget.channel.sink.close();
    super.dispose();
  }
}

Mui手机端实现移动端
MUI组件地址:http://dev.dcloud.net.cn/mui/snippet/
图标不足就用iconFont 地址 https://www.iconfont.cn/
调用android 用H5+ 地址:http://www.html5plus.org/doc/zh_cn/navigator.html

页面效果
在这里插入图片描述

Netty是一款基于NIO的网络通讯框架,它提供了高性能、高可靠性的网络编程能力,因此可以用来实现即时通讯。以下是一个简单的使用Netty实现即时通讯的示例: 1. 创建一个Netty的Server端和Client端 ```java // Server端 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); // 绑定端口,开始接收进来的连接 ChannelFuture f = b.bind(port).sync(); // 等待服务器 socket 关闭 。 // 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。 f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } // Client端 EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ClientHandler()); } }); // 连接服务端 ChannelFuture f = b.connect(host, port).sync(); // 等待连接关闭 f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } ``` 2. 编写ServerHandler和ClientHandler ```java // ServerHandler public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // 处理客户端发送过来的消息 ByteBuf in = (ByteBuf) msg; try { System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8)); // 将消息返回给客户端 ctx.write(in); ctx.flush(); } finally { ReferenceCountUtil.release(msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 当出现异常时关闭连接 cause.printStackTrace(); ctx.close(); } } // ClientHandler public class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { // 发送消息给服务端 ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Server", CharsetUtil.UTF_8)); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // 处理服务端返回的消息 ByteBuf in = (ByteBuf) msg; try { System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8)); } finally { ReferenceCountUtil.release(msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 当出现异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 这样,我们就可以用Netty实现简单的即时通讯了。当然,实际应用中还需要考虑更多的因素,例如协议的定义和解析、消息的组装和拆解等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值