初步搭建Springboot+Netty+Websoket

本文介绍了如何使用Springboot结合Netty实现WebSocket服务。首先通过初始化ServerBootstrap创建Netty服务入口,接着配置channel处理心跳检测和消息请求。最后在Springboot启动时启动Netty服务。提供了一个简单的测试代码案例,并分享了源码仓库链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这些天需要用java做一个简单的合成类小游戏,准备使用spring-websoket+stomp实现的。但之前做过一个,同时也想尝试一下netty的魅力。

1.初始化ServerBootstrap,创建netty服务入口
@Component
public class WSServer {
   

	private static class SingletionWSServer {
   
		static final WSServer instance = new WSServer();
	}
	
	public static WSServer getInstance() {
   
		return SingletionWSServer.instance;
	}
	
	private EventLoopGroup mainGroup;
	private EventLoopGroup subGroup;
	private ServerBootstrap server;
	private ChannelFuture future;
	
	public WSServer() {
   
		mainGroup = new NioEventLoopGroup();
		subGroup = new NioEventLoopGroup();
		server = new ServerBootstrap();
		server.group(mainGroup, subGroup)
			.channel(NioServerSocketChannel.class)
			.childHandler(new WSServerInitialzer());
	}
	
	public void start() {
   
		this.future = server.bind(26387);
		System.err.println("started netty websocket server...");
	}
}
2.初始化channel,处理消息
public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {
   

	@Override
	protected void initChannel(SocketChannel ch) {
   
		ChannelPipeline pipeline = ch.pipeline();

		//使用http编解码
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(new ChunkedWriteHandler());
		pipeline.addLast(new HttpObjectAggregator(1024*64));
		
		//心跳检测,读空闲30s触发,写空闲30s,都空闲60s
		pipeline.addLast(new IdleStateHandler(30, 30, 60));
		pipeline.addLast(new HeartBeatHandler());

		//websocket访问路由 /ws
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		
		//定义handler处理请求
		pipeline.addLast
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值