Netty4.X 学习(一)

Server:

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import com.netty.utils.*;

public class HelloServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Log.logInfo(">>>>>> I‘m server.");
        // System.out.println(">>>>>> I‘m server.");
        String msg = "Hello world\n";
        ByteBuf encoded = ctx.alloc().buffer(msg.length());
        encoded.writeBytes(msg.getBytes());
        ctx.write(encoded);
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //Log.logInfo("server receive message:" + msg);
        // System.out.println("服务器收到的消息:" + msg);
        ByteBuf in = (ByteBuf) msg;
        try {
            if (in.isReadable()) { // (1)
                String str = in.toString(CharsetUtil.US_ASCII);
                Log.logInfo("server receive message:" + str);
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }

    }
}
package com.netty.example.PrintHello;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class HelloWorldServer {
    public static void main(String[] args) {
        //EventLoop 代替原来的 ChannelFactory
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // server端采用简洁的连写方式,client端才用分段普通写法。
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new HelloServerHandler());
                        }
                    }).option(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = serverBootstrap.bind(8000).sync();
            f.channel().closeFuture().sync();
            System.out.println("TCP服务器已启动");
        } catch (InterruptedException e) {
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

运行后可以在终端直接通过telnet命令连接:

telnet localhost 8000

 

client:

package com.netty.example.PrintHello;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

public class HelloClientHandler  extends ChannelInboundHandlerAdapter{
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(">>>>> I‘m client.");
//        ctx.write("Hello world!");
//        ctx.flush();
        String msg = "Are you ok?";  
        ByteBuf encoded = ctx.alloc().buffer(msg.length());  
        encoded.writeBytes(msg.getBytes());  
        ctx.write(encoded);  
        ctx.flush(); 
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  throws Exception{
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { // (1)
                System.out.println("client收到服务器的消息:" + msg);
                System.out.print((char) in.readByte());
                System.out.flush();
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }
    }
}
package com.netty.example.PrintHello;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class HelloWorldClient {
    public static void main(String[] args) {
        // Client服务启动器 3.x的ClientBootstrap 改为Bootstrap,且构造函数变化很大,这里用无参构造。
        Bootstrap bootstrap = new Bootstrap();
        // 指定channel类型
        bootstrap.channel(NioSocketChannel.class);
        // 指定Handler
        bootstrap.handler(new HelloClientHandler());
        // 指定EventLoopGroup
        bootstrap.group(new NioEventLoopGroup());
        // 连接到本地的8000端口的服务端
        bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
    }
}

 

Netty4.X 学习(一),布布扣,bubuko.com

Netty4.X 学习(一)

上一篇:MVC中异常: An exception of type 'System.Data.ProviderIncompatibleException' occurred in EntityFramework.dll的一种解决办法


下一篇:CSS选择器的浏览器支持