BungeeMain / src / main / java / com / lifeknight / relaymcbungeemain / network / MessageServer.java
MessageServer.java
Raw
package com.lifeknight.relaymcbungeemain.network;

import com.lifeknight.relaymcbungeemain.Main;
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 java.util.concurrent.TimeUnit;

public class MessageServer {
    private static MessageServer instance = null;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    private final int port;

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

    public void run() throws Exception {
        this.bossGroup = new NioEventLoopGroup();
        this.workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(this.bossGroup, this.workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new MessageCoder.MessageEncoder(), new MessageCoder.MessageDecoder(), new MessageServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture channelFuture = serverBootstrap.bind(this.port).sync();

            channelFuture.channel().closeFuture().sync();
        } finally {
            this.workerGroup.shutdownGracefully();
            this.bossGroup.shutdownGracefully();
        }
    }

    public void stop() {
        if (!this.workerGroup.isShutdown()) this.workerGroup.shutdownGracefully();
        if (!this.bossGroup.isShutdown()) this.bossGroup.shutdownGracefully();
    }

    public static void start(int port) {
        instance = new MessageServer(port);
        Main.info("Opening message server on port %d.", port);
        Main.async(() -> {
            try {
                instance.run();
            } catch (Exception exception) {
                Main.error("An error occurred while starting or running the message server: %s", exception.getMessage());
                Main.info("Retrying in 10 seconds.");
                Main.schedule(() -> start(port), 10, TimeUnit.SECONDS);
            }
        });
    }

    public static void end() {
        if (instance != null) instance.stop();
    }
}