Java tutorial
/* * Copyright 2016 Zhongan.com All right reserved. This software is the * confidential and proprietary information of Zhongan.com ("Confidential * Information"). You shall not disclose such Confidential Information and shall * use it only in accordance with the terms of the license agreement you entered * into with Zhongan.com. */ package com.dingwang.netty.client; import com.dingwang.netty.decoder.PersonDecoder; import com.dingwang.netty.encoder.PersonEncoder; import com.dingwang.netty.handler.PersonInHandler; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; /** * DiscardClient.java??TODO ?? * * @author wangding_91@163.com 2016218 ?4:37:39 */ public class PersonClient { private int port; private String host; public PersonClient(int port, String host) { this.port = port; this.host = host; } public void run() { EventLoopGroup workerGroup = new NioEventLoopGroup(10); //BootStrapServerBootstrap,???channel?channel Bootstrap b = new Bootstrap(); //?EventLoopGroup?bossworkder //??boss b.group(workerGroup); //NioServerSocketChannelNioSocketChannel,channel b.channel(NioSocketChannel.class); //??ServerBootstrap?childOption()SocketChannelchannel b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new PersonEncoder(), new PersonDecoder(), new PersonInHandler()); } }); ChannelFuture f; try { //connect()bind() f = b.connect(host, port).sync(); ChannelPool.setChannel(f.channel()); // Person p = new Person(); // p.setAge(10); // p.setName("dw"); // f.channel().writeAndFlush(p); // Thread.currentThread().sleep(1000); // // p.setName("test"); // f.channel().writeAndFlush(p); // f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // workerGroup.shutdownGracefully(); } } }