Netty实现简单的websocketServer

1、pom文件

   <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.75.Final</version>
   </dependency>

2、只处理文本消息的 NettyWebSocketHandler

package com.example.demo.http;


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

// 只接受TextWebSocketFrame  文本消息
public class NettyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端建立连接,通道开启!");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接,通道关闭!");

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("客户端收到服务器数据:" + msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("收到: " + msg.text()));

    }

}

3、

NettyWebsocketServer
package com.example.demo.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class NettyWebsocketServer {

    /**
     * host
     */
    private final static String host = "0.0.0.0";

    /**
     * 端口号
     */
    private final static Integer port = 18085;
    public static void main(String[] args) {
        start();
    }

    /**
     * netty服务端启动方法
     */
    public static void start() {
        log.info("netty websocket start begin ");
        EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossEventLoopGroup, workerEventLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    //开启tcp nagle算法
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //开启长连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel c) {
                            c.pipeline().addLast(new HttpServerCodec())  // // HTTP 协议解析,用于握手阶段
                                    .addLast(new HttpObjectAggregator(512 * 1024))
                                    .addLast(new WebSocketServerCompressionHandler())  // WebSocket 数据压缩扩展
                                    //  // WebSocket 握手、控制帧处理
                                    .addLast(new WebSocketServerProtocolHandler("/", "WebSocket", true, 65536 * 10))
                                    .addLast(new NettyWebSocketHandler());

                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();

            log.info("netty websocket start at port " + port);

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("netty wensocket start exception,", e);
        } finally {
            log.info("netty websocket  shutdown bossEventLoopGroup&workerEventLoopGroup gracefully");
            bossEventLoopGroup.shutdownGracefully();
            workerEventLoopGroup.shutdownGracefully();
        }
    }
}

4、客户端连接测试

Websocket在线测试-Websocket接口测试-Websocket模拟请求工具

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值