首页 > 代码库 > Netty 服务器端DEMO

Netty 服务器端DEMO

package Demo;

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

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;

public class NIOServerDemo extends SimpleChannelUpstreamHandler {

/**
*
* @param args
*/
public static void main(String[] args) {
// server服务启动器
ServerBootstrap server = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
server.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
// TODO Auto-generated method stub
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decode", new StringDecoder());
pipeline.addLast("encode", new StringDecoder());
pipeline.addLast("thread", new NIOServerDemo());
return pipeline;
}
});
server.bind(new InetSocketAddress(8000));
System.out.println("服务已启动等待客户端连接……");
}

@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
//当有客户端连接上服务器执行的方法
System.out.println(e.getValue().toString() + "客户端已连接上服务器!");
}

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
//接收到客户端传来的数据进行相应处理并回复客户端
System.out.println("客户端信息:" + e.getChannel().getRemoteAddress());
System.out.println("服务器信息:" + e.getChannel().getLocalAddress());
System.out.println("接收到的消息:" + e.getMessage().toString());
e.getChannel().write(
ChannelBuffers.wrappedBuffer(e.getMessage().toString()
.getBytes()));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
//当客户端掉线触发的方法
System.out.println("客户端"+ctx.getChannel().getRemoteAddress()+"是否断线:"+("远程主机强迫关闭了一个现有的连接。").equals(e.getCause().getMessage()));
}
}

Netty 服务器端DEMO