Netty - WebSocket协议

本文介绍了如何使用Netty框架实现WebSocket协议。从前言开始,详细讲解了MyServer的配置,接着阐述了MyTextWebSocketFrameHandler的处理逻辑,并提供了hello.html用于建立连接。最后展示了运行效果和协议转换过程。

前言

websockt是需要依赖http1.1 然后返回其响应码101 再开始由http协议转为 webSocket

1、MyServer

/**
 * @author wzcstart
 * @date 2021/6/30 - 1:49
 */
public class MyServer {
    public static void main(String[] args) throws Exception{


        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))//netty自带得日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //拿到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
 
Netty是一个高性能、事件驱动、异步非阻塞的IO Java开源框架,可用于建立高性能的网络服务器和客户端程序,支持WebSocket协议。以下简述Java中使用Netty实现WebSocket的使用方法及给出示例代码。 ### 使用方法 1. **添加依赖**:在Maven项目中,需要在`pom.xml`文件里添加Netty的依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.72.Final</version> </dependency> ``` 2. **创建Netty服务器**:要创建一个Netty服务器来处理WebSocket连接,一般需要以下步骤: - 初始化`EventLoopGroup`,用来处理I/O操作。 - 创建`ServerBootstrap`,配置服务器启动参数。 - 添加`ChannelInitializer`,对`ChannelPipeline`进行配置。 - 绑定端口并启动服务器。 3. **处理WebSocket握手和消息**:在`ChannelPipeline`中添加`HttpServerCodec`、`HttpObjectAggregator`和`WebSocketServerProtocolHandler`来处理HTTP请求和WebSocket握手,同时自定义`ChannelInboundHandlerAdapter`来处理WebSocket消息。 ### 示例代码 以下是一个简单的Java使用Netty实现WebSocket服务器的示例代码: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; 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.stream.ChunkedWriteHandler; public class NettyWebSocketServer { private final int port; public NettyWebSocketServer(int port) { this.port = port; } public void run() throws Exception { 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 { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); pipeline.addLast(new NettyWebSocketServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; new NettyWebSocketServer(port).run(); } } import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { String request = msg.text(); System.out.println("Received message: " + request); ctx.channel().writeAndFlush(new TextWebSocketFrame("Server received: " + request)); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { System.out.println("Client connected: " + ctx.channel().id().asShortText()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { System.out.println("Client disconnected: " + ctx.channel().id().asShortText()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 上述代码实现了一个简单的Netty WebSocket服务器,服务器监听8080端口,接收客户端发送的文本消息并返回响应。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值