Netty學習筆記 (實驗篇)二

此次實驗要用netty實現一個EchoServer,Echo Protocol 的定義在這裏http://tools.ietf.org/html/rfc862 html

1.服務器端監聽端口7 (因爲Linux下普通用戶沒法使用1024如下的端口,所以綁定7777) java

2.客戶端鏈接服務器 後發送一條數據 bootstrap

3.服務器把接收到的數據直接返回給客戶端 服務器

代碼以下: socket

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 ide

咱們經過打印出的日誌能夠看到,服務器端先接收到了Hello Kugou  而後又直接寫回給了客戶端。 oop

相關文章
相關標籤/搜索