Netty学习笔记 (实验篇)二

这次实验要用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  然后又直接写回给了客户端。

转载于:https://my.oschina.net/ccdvote/blog/137962

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值