Spring-boot集成Netty做websocket服务端

spring-boot-websocket-netty-server, 依赖spring-boot-parent

 

Spring Boot: user notifications with web socket

This example will shows how to send notifications, via web socket, to specific logged-in users.

Could be useful, for example, if you are trying to implement a real-time user notification system.

Build and run

springboot启动后: http://localhost/

Configurations

<dependency>
	<groupId>io.netty</groupId>
	<artifactId>netty-all</artifactId>
	<version>4.1.12.Final</version>
</dependency>
@SpringBootApplication
public class NettyWebSocketServerApplication implements CommandLineRunner{
	@Autowired
	private ChatServer chatServer;

    public static void main(String[] args) {
        SpringApplication.run(NettyWebSocketServerApplication.class, args);
    }
    
    @Bean
    public ChatServer chatServer() {
    	return new ChatServer();
    }

	@Override
	public void run(String... args) throws Exception {
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9090);
		ChannelFuture future = chatServer.start(address);

		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				chatServer.destroy();
			}
		});

		future.channel().closeFuture().syncUninterruptibly();
	}
}
@Override
	protected void initChannel(Channel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		//处理日志
		pipeline.addLast(new LoggingHandler(LogLevel.INFO));
		
		//处理心跳
		pipeline.addLast(new IdleStateHandler(0, 0, 1800, TimeUnit.SECONDS));
		pipeline.addLast(new ChatHeartbeatHandler());
		
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(new ChunkedWriteHandler());
		pipeline.addLast(new HttpObjectAggregator(64 * 1024));
		pipeline.addLast(new HttpRequestHandler("/ws"));
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		pipeline.addLast(new TextWebSocketFrameHandler(group));		
	}

Prerequisites

  • Java 8
  • Maven > 3.0

From terminal

Go on the project's root folder, then type:

$ mvn spring-boot:run
项目完整路径:Spring-boot-netty-websocket

相关文章

谷歌翻译不能用了怎么办?最近有很多用户发现谷歌浏览器翻译...
ios17有不少新功能,此次更新重点升级了电话和短信的功能,新...
什么是IP地址?IP地址有什么用? 很简单,IP是整个TCP/IP协议...
网上找到的动图下载到本地保存时格式却成了webp,想要发表情...
小米手机一开相机就死机怎么处理? 处理手机一开相机就死机的...
充电宝押金什么时候可以退?具体操作充电宝退押金的操作步骤...