| | |
| | | |
| | | private String host; |
| | | private int port; |
| | | public Channel defaultChannel; |
| | | public static Channel defaultChannel; |
| | | |
| | | |
| | | public ClientEngine(String host, int port) { |
| | |
| | | @Override |
| | | public void run() { |
| | | try { |
| | | |
| | | startClient(); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | |
| | | } |
| | | |
| | | public void startClient() throws Exception { |
| | | if(defaultChannel != null){ |
| | | log.info("-----IP={},连接存在,直接使用",host); |
| | | return; |
| | | } |
| | | EventLoopGroup group = new OioEventLoopGroup(); |
| | | Bootstrap b = new Bootstrap(); |
| | | //默认长连接 |
| | |
| | | @Override |
| | | public void operationComplete(ChannelFuture arg0) throws Exception { |
| | | if (channelFuture.isSuccess()) { |
| | | log.info("-----IP={},连接成功"); |
| | | log.info("-----IP={},连接成功",host); |
| | | } else { |
| | | log.info("-----IP={},连接失败,自动关闭线程"); |
| | | log.info("-----IP={},连接失败,自动关闭线程",host); |
| | | channelFuture.cause().printStackTrace(); |
| | | group.shutdownGracefully(); // 关闭线程组 |
| | | } |
| | |
| | | return InvokeResult.SOCKET_NOT_CREATE; |
| | | } |
| | | if (!defaultChannel.isActive()) { |
| | | defaultChannel = null; |
| | | return InvokeResult.CHANNEL_CLOSED; |
| | | } |
| | | |
| | |
| | | } |
| | | |
| | | |
| | | public Channel getChannel() { |
| | | public static Channel getChannel() { |
| | | return defaultChannel; |
| | | } |
| | | |
| | | public static void add2ChannelMap(String key, Channel channel) { |
| | | public void add2ChannelMap(String key, Channel channel) { |
| | | clientChannelMap.put(key, channel); |
| | | } |
| | | |
| | |
| | | return channel; |
| | | } else { |
| | | channel.close(); |
| | | defaultChannel = null; |
| | | } |
| | | return null; |
| | | } |
| | |
| | | return InvokeResult.SOCKET_NOT_CREATE; |
| | | } |
| | | if (!channel.isActive()) { |
| | | defaultChannel = null; |
| | | return InvokeResult.CHANNEL_CLOSED; |
| | | } |
| | | channel.writeAndFlush(Unpooled.copiedBuffer(BytesUtil.hexStrToBytes(hex))).sync(); |