package com.example.myproject.demo.service.NettyExample;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
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 io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
/**
* 客户端
*/
public class NettyClient {
public static void main(String[] args) throws Exception {
String host = "127.0.0.1";
int port = 8080;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
// b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(
new RequestDataEncoder(),
new ResponseDataDecoder(),
new ClientHandler(),
new ClientOutHandler())
.addLast(new LoggingHandler(LogLevel.INFO));
}
});
ChannelFuture sync = b.connect(host, port).sync();
Channel channel = sync.channel();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line;
while(!"over".equals(line = bufferedReader.readLine())){
RequestData msg = new RequestData();
int length = line.getBytes().length;
msg.setIntValue(length);
msg.setStringValue(line);
channel.writeAndFlush(msg);
}
sync.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}