package com.szpg.plc.server; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.apache.log4j.Logger; import java.net.InetSocketAddress; public class ACUClient { private final Logger logger = Logger.getLogger(this.getClass().getName()); private final String host; private final int port; private Channel channel; private String acucode; //ACU编码 private String net; //网络号 private String node; //节点号 private String unit; //单元号 private String flag; //标段标志 public ACUClient(String host, int port) { this.host = host; this.port = port; } public String getHost() { return host; } public Channel getChannel() { return channel; } public void setChannel(Channel channel) { this.channel = channel; } public String getAcucode() { return acucode; } public void setAcucode(String acucode) { this.acucode = acucode; } public String getNet() { return net; } public void setNet(String net) { this.net = net; } public String getNode() { return node; } public void setNode(String node) { this.node = node; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } @Override public String toString() { return "ACUClient[code=" + acucode + ", host=" + host + ", port=" + port + "]"; } /** * 返回保存在Map中的键值 * @return */ public String getKey() { return host + ":" + port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup();//处理各种请求,如处理链接请求,发送接收数据等 try { Bootstrap boot = new Bootstrap();//配置整个netty,串联起各组件 boot.group(group); boot.channel(NioSocketChannel.class); boot.remoteAddress(new InetSocketAddress(host, port)); //配置handler boot.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ACUClientHandler()); } }); //注册监听事件,来判断操作的成功或失败 ChannelFuture future = boot.connect().sync(); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // 连接成功 logger.info(future.channel().remoteAddress() + "连接成功"); } else { logger.error(future.channel().remoteAddress() + "连接失败"); future.cause().printStackTrace(); } } }); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } }