这次实验要用netty实现一个EchoServer,Echo Protocol 的定义在这里http://tools.ietf.org/html/rfc862
1.服务器端监听端口7 (由于Linux下普通用户无法使用1024以下的端口,因此绑定7777)
2.客户端连接服务器 后发送一条数据
3.服务器把接收到的数据直接返回给客户端
代码如下:
package netty.learn.echo;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is a EchoServer implements the ECHO protocol
* User: mzy
* Date: 13-6-16
* Time: 下午3:13
* Version:1.0.0
*/
class EchoHandler extends ChannelInboundHandlerAdapter{
Logger log = Logger.getLogger(EchoHandler.class.getName());
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageList<Object> msgs) throws Exception {
ctx.write(msgs);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.log(Level.WARNING,cause.getMessage());
ctx.close();
}
}
public class EchoServer {
private int port;
public EchoServer(int port) {
this.port = port;
}
public void run(){
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup worker = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(boss,worker).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,100)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.INFO),new EchoHandler());
}
});
try {
b.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args) {
new EchoServer(7777).run();
}
}
这样服务器端就写好了,对比实验一中的DiscardServer 不难发现基本上除了Handler之外没有什么变化,这样TimeServer中的代码其实可以做为一个模板来使用。
下面我们用nc来测试一下 EchoServer
我们通过打印出的日志可以看到,服务器端先接收到了Hello Kugou 然后又直接写回给了客户端。