1.server
package example.helloword.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import example.helloword.NetConstant;

public class Server
{
private static Server server = new Server();
private ServerBootstrap bootstrap;
private Server()
{}
public static Server getInstance()
{
return server;
}
public void start()
{
bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(), Executors
.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ServerPipelineFactory());
bootstrap.bind(new InetSocketAddress(NetConstant.server_port));
}
public void stop()
{
bootstrap.releaseExternalResources();
}
public static void main(String[] args)
{
Server server = Server.getInstance();
server.start();
}
}
2.ServerPipelineFactory
package example.helloword.server;

import static org.jboss.netty.channel.Channels.pipeline;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

public class ServerPipelineFactory implements ChannelPipelineFactory
{
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipleline = pipeline();
pipleline.addLast("encode", new StringEncoder());
pipleline.addLast("decode", new StringDecoder());
pipleline.addLast("handler", new ServerHandler());
return pipleline;
}
}
3.handle
package example.helloword.server;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class ServerHandler extends SimpleChannelUpstreamHandler
{
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception
{
System.out.println("recive message,message content:" + e.getMessage());
e.getChannel().write("byte");
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception
{
e.getChannel().close();
}
}
clinet:










































































































































































