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

com.bizmda.bizsip.sink.connector.netty.NettyClient Maven / Gradle / Ivy

The newest version!
package com.bizmda.bizsip.sink.connector.netty;
import com.bizmda.bizsip.common.BizUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author 史正烨
 */
@Component
@Slf4j
public class NettyClient {

    private final EventLoopGroup group = new NioEventLoopGroup();
    private final Bootstrap bootstrap = new Bootstrap();

    @Value("${netty.port}")
    private Integer port;

    @Value("${netty.host}")
    private String host;

    public NettyClient(String host,Integer port) {
        this.host = host;
        this.port = port;
        this.bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new NettyClientInitializer());
    }
    /**
     * 发送消息
     */
    public byte[] call(byte[] msg) {
        //连接服务器
        ChannelFuture future;
        try {
            future = bootstrap.connect(this.host, this.port).sync();
        } catch (InterruptedException e) {
            log.error("连接服务器失败",e);
            Thread.currentThread().interrupt();
            return new byte[0];
        }
        future.channel().writeAndFlush(msg);
        log.trace("Channel通道写入报文:\n{}", BizUtils.buildHexLog(msg));
        //当通道关闭了,就继续往下走
        try {
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("通联关闭失败",e);
            Thread.currentThread().interrupt();
            return new byte[0];
        }
        //接收服务端返回的数据
        AttributeKey key = AttributeKey.valueOf("ServerData");
        return future.channel().attr(key).get();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy