1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| package com.redisc;
import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.io.IOException;
public class Client { static final Logger log = LoggerFactory.getLogger(Client.class);
public static void main(String[] args) throws IOException, InterruptedException { for (int i = 0; i < 10; i++) { send(); } }
public static void send() { NioEventLoopGroup worker = new NioEventLoopGroup();
try { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.group(worker); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ByteBuf byteBuf = ctx.alloc().buffer(16); byteBuf.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}); ctx.writeAndFlush(byteBuf); ctx.channel().close(); } }); } }); ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8000); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { log.error("error", e); } finally { worker.shutdownGracefully(); } } }
|