1.客户端代码示例
public class Client {
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8081"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
public static void main(String[] args) throws Exception {sendMessage("你好:Netty");}
public static void sendMessage(String content) throws InterruptedException{
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {Bootstrap b = new Bootstrap();b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("decoder", new StringDecoder());
p.addLast("encoder", new StringEncoder());
p.addLast(new ClientHandler());}});
ChannelFuture future = b.connect(HOST, PORT).sync();
future.channel().writeAndFlush(content);
future.channel().closeFuture().sync();
} finally {group.shutdownGracefully();}}}
2.创建ClientChannelInitializer类示例:
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline p = channel.pipeline();
p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
p.addLast(new ClientHandler());}}
3.创建ClientHandler类示例
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("ClientHandler Active");}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("--------");
System.out.println("ClientHandler read Message:"+msg);}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {cause.printStackTrace();ctx.close();}}
4.参考文档:https://www.cnblogs.com/Yintianhao/p/10181245.html