netty4.0使用

来源:互联网 发布:网络上最近挺火的歌曲 编辑:程序博客网 时间:2024/05/16 02:02

创建server端:



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.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ConstractorServerNetty {
    private void constractServerNetty() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap sbs = new ServerBootstrap();
            sbs.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .localAddress(10000)
            .childOption(ChannelOption.TCP_NODELAY,true)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                public void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new EchoServerHandler());
                }
            });
            ChannelFuture f = sbs.bind().sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new ConstractorServerNetty().constractServerNetty();
    }
}

server的handler:



import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundByteHandlerAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.***.mytest.utils.NumberUtil;

public class EchoServerHandler extends ChannelInboundByteHandlerAdapter {

    private  final Logger logger = LoggerFactory.getLogger(EchoServerHandler.class);
    
    @Override
    protected void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf bytebuf)
            throws Exception {
        boolean flag = ctx.hasInboundByteBuffer();
        if(flag) {
   
            //返回个副本,原bytebuf可读的字节
            //bytebuf = bytebuf.copy();
            //缓冲区实际可读字节数量
            int size = bytebuf.readableBytes();
            logger.debug("========bytebuf total  size ["+size+"]");
            int headerSize =0;
            if(size>4) {
                byte[] sizeByte = new byte[4];
                bytebuf.readBytes(sizeByte);
                headerSize = NumberUtil.byteArrayToInt(sizeByte);
                logger.debug("=======header size ["+headerSize+"]");
            }
            
            if(headerSize==0) {
                logger.debug("====headerSize is not enough=====");
                return;
            }
            
            byte[] received = new byte[headerSize];
            //将信息从bytebuf读入到result中
            bytebuf.readBytes(received);
            logger.debug("==================="+new String(received,"utf-8"));
           
 
 
            ByteBuf out = ctx.nextOutboundByteBuffer();     
            String returnInfo = "It's ok!";

             returnInfo+="\n";     //加上\n  以便inputStream转换bufferedReader读取数据
            out.writeBytes(returnInfo.getBytes("utf-8"));
            ctx.flush();
        }else {
            logger.debug("========inboundByteBuffer has not info===========");
        }
    }
}

客户端:



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;

import com.***.mytest.utils.NumberUtil;

public class Client {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = null;
        OutputStream out = null;
        InputStream in = null;
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress("127.0.0.1",10000));
            out = socket.getOutputStream();
            String s = "abcccc";
            int longer = s.length();
            byte[] size = NumberUtil.intToByteArray(longer);
            
            pw = new PrintWriter(out);
            pw.write(new String(size,"utf-8"));
            pw.write(s);
            pw.flush();
            out.flush();
            
            in = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            System.out.println(reader.readLine()+"  client received info "); 
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(pw!=null) {
                pw.close();
            }
            if(out!=null) {
                out.close();
            }
            if(in!=null) {
                in.close();
            }
        }
    }
}

4字节数组与int相互转化,网络传输中很多用前4个字节代表数据内容的长度。

public class NumberUtil {

     public static byte[] intToByteArray(int num) {   
         byte[] bytes = new byte[4];
            bytes[0] = (byte) (num >> 24);
            bytes[1] = (byte) (num >> 16);
            bytes[2] = (byte) (num >> 8);
            bytes[3] = (byte) (num);
            return bytes;
     }
    
     public static int byteToInt(byte[] bytes){
         return Integer.valueOf(""+ (((bytes[0] & 0x000000ff) << 24) | ((bytes[1] & 0x000000ff) << 16)
                 | ((bytes[2] & 0x000000ff) << 8) | (bytes[3] & 0x000000ff)));
     }

}




原创粉丝点击