Newer
Older
rain_receiver / src / main / java / com / casic / client / Client.java
package com.casic.client;

import com.casic.config.ServerPort;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Client extends Thread {

    @Autowired
    private ServerPort serverPort;

    private volatile String sendMsg;

    public void setSendMsg(String sendMsg) {
        this.sendMsg = sendMsg;
    }

    @Override
    public void run() {
        super.run();
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new Clientinitializer());
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", serverPort.getPort()).sync();
            Channel channel = channelFuture.channel();
            channel.writeAndFlush(sendMsg);
        } catch (Exception ex) {
            log.error("发送异常");
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

//    public void send(String sendMsg) throws Exception {
//        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
//        try {
//            Bootstrap bootstrap = new Bootstrap();
//            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
//                    .handler(new Clientinitializer());
//            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", serverPort.getPort()).sync();
//            Channel channel = channelFuture.channel();
//            channel.writeAndFlush(sendMsg);
//        } finally {
//            eventLoopGroup.shutdownGracefully();
//        }
//    }

}