栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Netty10-WebSocket长连接开发

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Netty10-WebSocket长连接开发

Netty 通过WebSocket编程实现服务器和客户端长连接

实例要求:

  1. Http协议是无状态的, 浏览器和服务器间的请求响应一次,下一次会重新创建连接.
  2. 要求:实现基于webSocket的长连接的全双工的交互
  3. 改变Http协议多次请求的约束,实现长连接了, 服务器可以发送消息
    给浏览器
  4. 客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知
Server
package com.atguigu.netty.webSoket;

import com.atguigu.netty.NettyHeartBeat.HeartServerhandle;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.Socket;
import java.util.concurrent.TimeUnit;



public class Server {
    public static void main(String[] args) throws InterruptedException {
        //线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //在bossGroup 关联一个日志处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            //因为基于http协议 因此要使用http的编解码器
                            pipeline.addLast(new HttpServerCodec());
                            //是以块方式写 添加此处理器
                            pipeline.addLast(new ChunkedWriteHandler());

                            // 说明
                            // 1.Http数据传输在传输过程中是分段的 就是可以将多个段聚合起来
                            // 2.这就是为什么当浏览器发送大量数据时就会发出多次http请求 因为数据是分段的
                            pipeline.addLast(new HttpObjectAggregator(8192));

                            // 说明
                            // 1. 对于Websocket数据他的数据是以帧(frame)的形式传递的
                            // 2. 可以看到webSocketFrame下面有6个子类
                            // 3. 浏览器请求时 他的形式 ws://localhost:7000/xxx 表示请求的uri
                            // 4. WebSocketServerProtocolHandler 将一个http协议升级为WebSocket(ws)协议,保持长连接
                            // 5. 通过一个状态码来切换的
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello2"));

                            //自定义的Handle 处理浏览器请求(基于帧的形似处理数据)
                            pipeline.addLast(new Handle());

                        }
                    });

            //启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            //监关闭事件
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

Handle
package com.atguigu.netty.webSoket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;



public class Handle extends SimpleChannelInboundHandler {

    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // id 为唯一标识
        System.out.println("Web客户端已连接 Long" + ctx.channel().id().asLongText());
        System.out.println("Web客户端已连接 Short" + ctx.channel().id().asShortText());

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved 触发" + ctx.channel().id().asLongText());
    }

    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生"+ cause.getMessage());
        //关闭通道
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器端收到消息:::" + msg.text());

        //回复浏览器
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间::"+ LocalDateTime.now() + msg.text()));
    }
}

HTML 即 客户端



    
    Title



    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/996218.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号