Netty解决粘包问题(二)

方案二:使用定长字符串   (FixedLengthFrameDecoder)

server:

package lqt.netty.code2;

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;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class Server {

	public static void main(String[] args) throws InterruptedException {
		EventLoopGroup pGroup=new NioEventLoopGroup();
		EventLoopGroup cGroup=new NioEventLoopGroup();
		ServerBootstrap b=new ServerBootstrap();
		b.group(pGroup, cGroup)
		.channel(NioServerSocketChannel.class)
		.option(ChannelOption.SO_BACKLOG,1024)							//设置TCP缓冲区
		.option(ChannelOption.SO_SNDBUF, 32*1024) 						//设置发送缓冲大小
		.option(ChannelOption.SO_RCVBUF,32*1024)						//设置接收缓冲大小
		.option(ChannelOption.SO_KEEPALIVE,true)						//保持连接
		.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new FixedLengthFrameDecoder(5));		//设置接收的长度
				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new ServerHandler());
				
			}
			
		});
		ChannelFuture cf=b.bind(8765).sync();
		System.out.println("server start ....");
		cf.channel().closeFuture().sync();
		pGroup.shutdownGracefully();
		cGroup.shutdownGracefully();
	}

}
//ServerHandler 
package lqt.netty.code2;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends ChannelHandlerAdapter{
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String request=(String)msg;
        System.out.println("Server: "+request);
        String response=request;
        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
    }
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

----------------------------------------------------------------------------------------------------------------------------------------

Client:

package lqt.netty.code2;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;


public class Client {

	public static void main(String[] args) throws InterruptedException {
		EventLoopGroup group =new NioEventLoopGroup();
		Bootstrap b=new Bootstrap();
		b.group(group)
		.channel(NioSocketChannel.class)
		.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new FixedLengthFrameDecoder(5));
				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new ClientHandler());
				
			}
		});
		ChannelFuture cf=b.connect("127.0.0.1", 8765).sync();
		System.out.println("client connected....");
		cf.channel().writeAndFlush(Unpooled.copiedBuffer("aaaaabbbbb".getBytes()));
		cf.channel().writeAndFlush(Unpooled.copiedBuffer("ccccccc".getBytes()));
		
		cf.channel().closeFuture().sync();
		group.shutdownGracefully();
	}

}
//ClientHandler 
package lqt.netty.code2;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelHandlerAdapter{
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			String response=(String)msg;
	        System.out.println("Client: "+response);
		}finally {
			ReferenceCountUtil.release(msg);
		}
        
    }
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值