Newer
Older
rain_receiver / src / main / java / com / casic / server / ReceiverServer.java
package com.casic.server;

import com.casic.config.ServerPort;
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 io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @description: 接收客户端传过来的数据,只做打印处理
 * @author: Stone
 * @create: 2019-01-10 19:52
 **/
@Slf4j
@Component
public class ReceiverServer {

    @Autowired
    private ReceiverServerHandler receiverServerHandler;
    @Autowired
    private ServerPort serverPort;

//    @PostConstruct
//    public void init() {
//        this.start();
//    }

    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        log.info("server bind port = {}", serverPort.getPort());

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap = serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap = serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        serverBootstrap = serverBootstrap.channel(NioServerSocketChannel.class);

        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) {
//                socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
//                socketChannel.pipeline().addLast(new ReceiverDecoder());
                socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast(receiverServerHandler);
            }
        });
        serverBootstrap = serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(serverPort.getPort()).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}