Netty client and server example

 

package com.snailteam.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
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.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Server Bootstrap
 * @author  
 *
 */
public class NServer {
	static final int PORT = 8080;

	public static void main(String[] args) {
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                         /**
                	Inbound: 1 ->2 ->3 ->n sequential processing
			Outbound: n ->n-1 ->n-2 .. ->1 Reverse order processing
                	 */
                	//new LengthFieldBasedFrameDecoder(1024*8*20, 0, 4,0,4) The maximum 1024*8*20 bits are the received data packets, from 0, the length of 4Byte is the data width, and then the byte after culling from 0, the length of 4Byte The data packet is sent to the subsequent handler chain for processing
                	ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG),new LengthFieldBasedFrameDecoder(1024*8*20, 0, 4,0,4), new NServerHandler());
                }
             });

            // Bind and start to accept incoming connections.
            b.bind(PORT).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
			e.printStackTrace ();
		} finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
	}
}

 

 

 

package com.snailteam.netty;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NServerHandler extends SimpleChannelInboundHandler<ByteBuf> {


	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
			throws Exception {
		String str = msg.toString(Charset.forName("UTF-8"));
		System.out.println("[ok]" +str );
		str = "Work hard"+str.substring(str.lastIndexOf(',')+1);
		ctx.writeAndFlush(Unpooled.wrappedBuffer(str.getBytes()));
	}
}

 

 

 

package com.snailteam.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
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.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
 * Client Bootstrap
 *
 */
public class Nclient {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch)
								throws Exception {
							//LengthFieldPrepender adds 4Bytes before the data to be sent to store the data width and sends it.
							ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG),new LengthFieldPrepender(4),
									new NclientHandler());

						}
					});

			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < 20; i++) {
				sb.append("People's Republic of China" + i + ",");
			}
			// Bind and start to accept incoming connections.
			Channel con = b.connect("localhost", NServer.PORT).sync().channel();
			
			for (int i = 0; i < 900; i++) {
				String str = sb.toString() + i;
				con.writeAndFlush(Unpooled.wrappedBuffer(str.getBytes())).sync().get();
				System.out.println(i);
			}
			con.close().sync();//Asynchronous exit
		} catch (InterruptedException e) {
			e.printStackTrace ();
		} finally {
			group.shutdownGracefully();
		}
	}
}

 

 

 

 

package com.snailteam.netty;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NclientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	
	@Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
        ctx.close();
    }
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
			throws Exception {
		System.out.println(msg.toString(Charset.forName("UTF-8")));
		
	}
}

 

 

 

package com.snailteam.netty;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
 

public class FrameDecoder extends ByteToMessageDecoder{
	int lengthFeildLength = 4;
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		 Object decoded = decode(ctx, in);
	        if (decoded != null) {
	            out.add(decoded);
	        }
	}

	private Object decode(ChannelHandlerContext ctx, ByteBuf in) {
		if(in.readableBytes()<lengthFeildLength)return null;//
		int index = in.readerIndex();
		int len ​​= in.readInt();//The size of the object in the parsing times package
		if(in.readableBytes()<len){//The content of the data packet is incomplete
			in.readerIndex(index);//重置readerIndex
			return null;
		}
		return in.readRetainedSlice(len);//Intercept a complete transcoding object.
	}

}

 

 

 

 

 

pom

<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-example</artifactId>
			<version>4.1.6.Final</version>
			<exclusions>
				<exclusion>
					<artifactId>netty-tcnative</artifactId>
					<groupId>io.netty</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-tcnative</artifactId>
			<version>1.1.33.Fork23</version>
			<classifier>windows-x86_64</classifier>
		</dependency>

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326640365&siteId=291194637