You are on page 1of 7

package org.arthur.

netty; import import import import import import import import import import import import import import import import import import import import java.net.InetSocketAddress; java.util.concurrent.Executors; org.jboss.netty.bootstrap.ClientBootstrap; org.jboss.netty.bootstrap.ServerBootstrap; org.jboss.netty.channel.Channel; org.jboss.netty.channel.ChannelFuture; org.jboss.netty.channel.ChannelFutureListener; org.jboss.netty.channel.ChannelHandlerContext; org.jboss.netty.channel.ChannelPipeline; org.jboss.netty.channel.ChannelPipelineFactory; org.jboss.netty.channel.ChannelStateEvent; org.jboss.netty.channel.Channels; org.jboss.netty.channel.ExceptionEvent; org.jboss.netty.channel.MessageEvent; org.jboss.netty.channel.SimpleChannelHandler; org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; org.jboss.netty.handler.codec.string.StringDecoder; org.jboss.netty.handler.codec.string.StringEncoder; org.junit.Test;

class HelloWorldServerHandler2 extends SimpleChannelHandler { public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { System.out.println("I am Server. Print Client Info:"); System.out.println(ctx.getChannel().getRemoteAddress()); ChannelFuture f = e.getChannel().write("Hello, World! I am Server."); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { Channel ch = future.getChannel(); ch.close(); } });

public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { System.out.println("Unexpected exception from downstream." + e.getCause()); e.getChannel().close(); }

class HelloWorldClientHandler2 extends SimpleChannelHandler { public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { String message = (String) e.getMessage(); System.out.println("I am Client. Print Server Info:"); System.out.println(message); e.getChannel().close(); } public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { System.out.println("Unexpected exception from downstream." + e.getCause());

e.getChannel().close();

/** * Netty VS MinaNettyPipelineMinaFilter * Netty * HttpsSSLPBRSTPText &Binary * NettyUDPNettyMina * @author Administrator * */ public class TestCase2 { public void testServer() { //channel ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); pipeline.addLast("handler", new HelloWorldServerHandler2()); return pipeline; } }); //channel,connection bootstrap.bind(new InetSocketAddress(8080)); }

public void testClient() { //channel,connection ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); //It means one same HelloWorldClientHandler2 instance is going to handle multiple Channels and consequently the data will be corrupted. //ChannelPipelineFactorypipeline bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); pipeline.addLast("handler", new HelloWorldClientHandler2()); return pipeline; } }); //channel(UDP),clientserver ChannelFuture future = bootstrap.connect(new InetSocketAddress( "localhost", 8080)); future.getChannel().getCloseFuture().awaitUninterruptibly(); bootstrap.releaseExternalResources(); }

@Test public void testNetty(){ testServer(); testClient(); } }

package org.arthur.netty; import import import import import import import import import import import import import import import import import import import import import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer; java.net.InetSocketAddress; java.util.concurrent.Executors; org.jboss.netty.bootstrap.ClientBootstrap; org.jboss.netty.bootstrap.ServerBootstrap; org.jboss.netty.buffer.ChannelBuffer; org.jboss.netty.channel.Channel; org.jboss.netty.channel.ChannelFactory; org.jboss.netty.channel.ChannelFuture; org.jboss.netty.channel.ChannelFutureListener; org.jboss.netty.channel.ChannelHandlerContext; org.jboss.netty.channel.ChannelPipeline; org.jboss.netty.channel.ChannelPipelineFactory; org.jboss.netty.channel.ChannelStateEvent; org.jboss.netty.channel.Channels; org.jboss.netty.channel.MessageEvent; org.jboss.netty.channel.SimpleChannelHandler; org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; org.jboss.netty.handler.codec.frame.FrameDecoder; org.junit.Test;

/** * POJOChannelBuffer */ class TimeServerHandler3 extends SimpleChannelHandler { @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { Persons person = new Persons("",31,10000.44); ChannelFuture future = e.getChannel().write(person); future.addListener(ChannelFutureListener.CLOSE);

class TimeClientHandler3 extends SimpleChannelHandler{ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Persons person = (Persons)e.getMessage(); System.out.println(person);

e.getChannel().close();

/** * FrameDecoder and ReplayingDecoder allow you to return an object of any type. * */ class TimeDecoder extends FrameDecoder { private final ChannelBuffer buffer = dynamicBuffer(); @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer channelBuffer) throws Exception { if(channelBuffer.readableBytes()<4) { return null; } if (channelBuffer.readable()) { // ,buf channelBuffer.readBytes(buffer, channelBuffer.readableBytes()); } int namelength = buffer.readInt(); String name = new String(buffer.readBytes(namelength).array(),"GBK"); int age = buffer.readInt(); double salary = buffer.readDouble(); Persons person = new Persons(name,age,salary); return person; } } class TimeEncoder extends SimpleChannelHandler { private final ChannelBuffer buffer = dynamicBuffer(); @Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Persons person = (Persons)e.getMessage(); buffer.writeInt(person.getName().getBytes("GBK").length); buffer.writeBytes(person.getName().getBytes("GBK")); buffer.writeInt(person.getAge()); buffer.writeDouble(person.getSalary()); Channels.write(ctx, e.getFuture(), buffer); }

class Persons{ private String name; private int age; private double salary; public Persons(String name,int age,double salary){ this.name = name; this.age = age; this.salary = salary; } public String getName() { return name; }

public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "Persons [name=" + name + ", age=" + age + ", salary=" + salary + "]"; } } public class TestCase5 { public void testServer() { ChannelFactory factory = new NioServerSocketChannelFactory(Executors.n ewCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new TimeEncoder(), new TimeServerHa } }); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); bootstrap.bind(new InetSocketAddress("localhost",9999));

ndler3());

public void testClient(){ //channel,connection ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new TimeDecoder()); pipeline.addLast("encoder", new TimeEncoder()); pipeline.addLast("handler", new TimeClientHandler3()); return pipeline; } }); //channel(UDP),clientserver ChannelFuture future = bootstrap.connect(new InetSocketAddress(

"localhost", 9999)); future.getChannel().getCloseFuture().awaitUninterruptibly(); bootstrap.releaseExternalResources();

@Test public void testNetty() { testServer(); testClient(); }

You might also like