客户端 和服务端差不多
注意 需要单独开线程 做netty , 如果不开线程会阻塞主线程(spring @Bean) , 客户端不能直接发送字符串 需要转换成Bytebuffer
public class NettyClient {
public static void main(String[] args) {
NioEventLoopGroup boss = new NioEventLoopGroup(1);
Bootstrap bootstrap = new Bootstrap().group(boss);
bootstrap.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg);
}
});
}
});
try {
ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 13140)).sync();
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture arg0) throws Exception {
if (future.isSuccess()) {
System.out.println("连接服务器成功");
} else {
System.out.println("连接服务器失败");
future.cause().printStackTrace();
boss.shutdownGracefully(); //关闭线程组
}
}
});
Executors.newFixedThreadPool(1).submit(()->{
Channel channel = future.channel();
while(true) {
channel.writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes()));
TimeUnit.SECONDS.sleep(2);
}
});
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
网友评论