package com.jpsoft.education.netty; import com.jpsoft.education.netty.hander.MyClientHandler; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import java.io.UnsupportedEncodingException; import java.util.concurrent.CountDownLatch; public class MyClientNetty { public static CountDownLatch countDownLatch = new CountDownLatch(1); public static CountDownLatch countDownLatch2 = new CountDownLatch(1); private String ip; private int port; private static ChannelFuture cf; private static EventLoopGroup bossGroup; public MyClientNetty(String ip, int port) { this.ip = ip; this.port = port; } public String sendRecv(String msg){ try { cf.channel().writeAndFlush(Unpooled.copiedBuffer(msg.getBytes())); MyClientNetty.countDownLatch.await(); return MyClientHandler.message; } catch (Exception e) { e.printStackTrace(); return null; } } public void connect() throws UnsupportedEncodingException, InterruptedException { this.action(); countDownLatch2.await(); } public void close() throws InterruptedException { cf.channel().closeFuture().sync(); bossGroup.shutdownGracefully(); } public void action() throws InterruptedException, UnsupportedEncodingException { bossGroup = new NioEventLoopGroup(); final Bootstrap bs = new Bootstrap(); ((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)bs.group(bossGroup)).channel(NioSocketChannel.class)).option(ChannelOption.SO_KEEPALIVE, true)).option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))).handler(new ChannelInitializer() { protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new ChannelHandler[]{new MyClientHandler()}); } }); (new Thread(new Runnable() { public void run() { try { MyClientNetty.cf = bs.connect(MyClientNetty.this.ip, MyClientNetty.this.port).sync(); MyClientNetty.countDownLatch2.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } })).start(); } public static void main(String[] args) { try { MyClientNetty myClientNetty = new MyClientNetty("127.0.0.1",9999); myClientNetty.connect(); String sendStr ="01 03 01 2c 00 0a"; System.out.println("客户端发送数据:"+sendStr); String result = myClientNetty.sendRecv(sendStr); System.out.println("客户端获取返回数据:"+result); if(result.contains(" ")){ result=result.replace(" ",""); System.out.println("客户端获取返回处理:"+result); } myClientNetty.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }