Skip to content

netty开发 websocket 服务

bash
package com.me.i4;

import com.me.i4.handler.WebSocketServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class WebsocketNettyServer {

    private int port=8081;


    public WebsocketNettyServer() {

    }
    public WebsocketNettyServer(int port) {
        this.port = port;
    }
    public void run() throws Exception {
          EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
          EventLoopGroup workers = new NioEventLoopGroup();
      try {
          ServerBootstrap serverBootstrap = new ServerBootstrap();
          serverBootstrap.group(eventLoopGroup, workers)
                  .channel(io.netty.channel.socket.nio.NioServerSocketChannel.class)
                  .childHandler(new ChannelInitializer<SocketChannel>(){
                      @Override
                      public  void initChannel(SocketChannel ch) throws Exception {
                          ChannelPipeline pipeline = ch.pipeline();
                          pipeline.addLast(new HttpServerCodec());
                          pipeline.addLast(new HttpObjectAggregator(65536));
                          pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                          pipeline.addLast(new WebSocketServerHandler());
                      }
                  });
          ChannelFuture future = serverBootstrap.bind(port).sync();

          future.channel().closeFuture().sync();
      }catch (Exception e)  {
          e.printStackTrace();
      }finally {
          workers.shutdownGracefully();
          eventLoopGroup.shutdownGracefully();
      }
    }
    public static void main(String[] args) throws Exception {

        WebsocketNettyServer server = new WebsocketNettyServer(8081);
        server.run();
    }
}