All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.linyuzai.connection.loadbalance.netty.sample.NettySampleServer Maven / Gradle / Ivy

There is a newer version: 2.7.1
Show newest version
package com.github.linyuzai.connection.loadbalance.netty.sample;

import com.github.linyuzai.connection.loadbalance.netty.concept.NettyLoadBalanceConcept;
import com.github.linyuzai.connection.loadbalance.netty.concept.NettyLoadBalanceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

@Getter
@RequiredArgsConstructor
public class NettySampleServer {

    private final NettyLoadBalanceConcept concept;

    @Setter
    private String group;

    public void send(String msg) {
        if (msg.endsWith("\n")) {
            concept.send(msg);
        } else {
            concept.send(msg + "\n");
        }
    }

    public void start(int port) throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer() {

                        @Override
                        protected void initChannel(@NonNull SocketChannel channel) {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new LineBasedFrameDecoder(1024));
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            if (group == null) {
                                pipeline.addLast(new NettyLoadBalanceHandler(concept));
                            } else {
                                pipeline.addLast(new NettyLoadBalanceHandler(concept, group));
                            }
                        }
                    });
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy