标签:des c style class blog code
对于Netty在这里就不做过多介绍了,详情咨询http://netty.io/wiki/user-guide-for-4.x.html
我们在使用netty的过程中肯定会遇到传输对象的情况,Netty4通过ObjectEncoder和ObjectDecoder来支持。
首先我们定义一个User对象,一定要实现Serializable接口:
import java.io.Serializable; /** * User: hupeng * Date: 14-6-3 * Time: 上午1:31 */ public class User implements Serializable { private int id; private String name; private String cardNo; private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "User{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ", cardNo=‘" + cardNo + ‘\‘‘ + ", description=‘" + description + ‘\‘‘ + ‘}‘; } }
然后定义一个客户端:
import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; public class ObjectTransferClient { private String host; private int port; private int messageSize; public ObjectTransferClient(String host, int port, int messageSize) { this.host = host; this.port = port; this.messageSize = messageSize; } public void run() throws InterruptedException { Bootstrap bootstrap = new Bootstrap(); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try { bootstrap.group(eventLoopGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new ObjectEncoder(), new ObjectDecoder(Integer.MAX_VALUE ,ClassResolvers.cacheDisabled(null)), new ObjectTransferClientHandler(messageSize)); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { final String host = "127.0.0.1"; final int port = 8080; final int messageSize = 200; new ObjectTransferClient(host, port, messageSize).run(); } }
以及客户端的一个handler
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class ObjectTransferClientHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = Logger.getLogger( ObjectTransferClientHandler.class.getName()); private final List<User> message; /** * Creates a client-side handler. */ public ObjectTransferClientHandler(int messageSize) { if (messageSize <= 0) { throw new IllegalArgumentException( "firstMessageSize: " + messageSize); } message = new ArrayList<User>(messageSize); for (int i = 0; i < messageSize; i ++) { User user = new User(); user.setId(i); user.setCardNo("420000" + i); user.setName("hu" +i); user.setDescription("你觉得这样好吗??真的好吗" + i); message.add(user); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send the message to Server ctx.writeAndFlush(message); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // you can use the Object from Server here System.out.println(msg); ctx.close(); } @Override public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.log( Level.WARNING, "Unexpected exception from downstream.", cause); ctx.close(); } }
然后是服务端:
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.serialization.ObjectDecoder; import io.netty.handler.codec.serialization.ObjectEncoder; public class ObjectTranferServer { private final int port; public ObjectTranferServer(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new ObjectEncoder(), new ObjectDecoder(Integer.MAX_VALUE,ClassResolvers.cacheDisabled(null)), new ObjectTransferServerHandler()); } }); // Bind and start to accept incoming connections. b.bind(port).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); } else { port = 8080; } new ObjectTranferServer(port).run(); } }
服务端Handler:
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.logging.Level; import java.util.logging.Logger; public class ObjectTransferServerHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = Logger.getLogger( ObjectTransferServerHandler.class.getName()); @Override public void channelRead( ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println(msg); ctx.write(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); ctx.close(); } @Override public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.log( Level.WARNING, "Unexpected exception from downstream.", cause); ctx.close(); } }
这里我传入的size为200的一个list对象。 当我把size增加到1000的时候,客户端和服务端都不报任何错误,但是也接收不到值。。具体原因还在寻找中,如果亲爱的你,可以指点一下我,那简直就是太好了。。。。
当然我们也可以采取其他方式,比如在客户端和服务端,通过json来序列化和反序列化传递,然后按照String来处理就行了
标签:des c style class blog code
原文地址:http://www.cnblogs.com/hupengcool/p/3766391.html