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模拟请求工具