標籤:factor sim one nio override current thread hand []
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