Spring Boot + Netty + WebSocket 实现消息推送

1

关于Netty

Netty 是一个利用 Java 的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的 API 的客户端/服务器框架。

2

Maven依赖

<dependencies>
 <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
 <dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.36.Final</version>
 </dependency>
</dependencies>

3

SpringBootApplication

启动器中需要new一个NettyServer,并显式调用启动netty。

@SpringBootApplication
public class SpringCloudStudyDemoApplication {
 public  static  void  main(String[] args) {
  SpringApplication.run(SpringCloudStudyDemoApplication.class,args);
  try {
   new NettyServer(12345).start();
   System.out.println("https://blog.csdn.net/moshowgame");
   System.out.println("http://127.0.0.1:6688/netty-websocket/index");
  }catch(Exception e) {
   System.out.println("NettyServerError:"+e.getMessage());
  }
 }
}

4

NettyServer

启动的NettyServer,这里进行配置

/**
 * NettyServer Netty服务器配置
 */
public class NettyServer {

    private final int port;

    public  NettyServer(int port) {
        this.port = port;
    }

    public  void  start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            sb.group(group, bossGroup) // 绑定线程池
 .channel(NioServerSocketChannel.class) // 指定使用的channel
 .localAddress(this.port)// 绑定监听端口
 .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
 @Override
  protected  void  initChannel(SocketChannel ch) throws Exception {
 System.out.println("收到新连接");

  //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
 ch.pipeline().addLast(new HttpServerCodec());

  //以块的方式来写的处理器
 ch.pipeline().addLast(new ChunkedWriteHandler());
 ch.pipeline().addLast(new HttpObjectAggregator(8192));
 ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
 ch.pipeline().addLast(new MyWebSocketHandler());
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值