码迷,mamicode.com
首页 > Web开发 > 详细

Netty 服务器端DEMO

时间:2017-02-10 14:35:40      阅读:209      评论:0      收藏:0      [点我收藏+]

标签: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

标签:factor   sim   one   nio   override   current   thread   hand   []   

原文地址:http://www.cnblogs.com/liaopengju/p/6386020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!