先上代码:
Client:
public class Client {
static int port = 8787;
static String host = "127.0.0.1";
public static void main(String[] args){
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 编码
ch.pipeline().addLast(new ObjectEncoder());
ch.pipeline().addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
ch.pipeline().addLast("protobufEncoder", new ProtobufEncoder());
}
});
// 连接服务端
Channel ch = b.connect(host, port).sync().channel();
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Message m = Message.newBuilder().setContent("random" + RandomUtils.nextInt(1, 10000)).build();
//Thread.sleep(1);
ch.writeAndFlush(m);
}
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
}catch(Exception e){
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
}
Server:
public class Server {
static int port = 8787;
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
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 {
ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
ch.pipeline().addLast(new ProtobufDecoder(CallMessage.getDefaultInstance()));
ch.pipeline().addLast(new ProtobufServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
// 服务器绑定端口监听
ChannelFuture f = b.bind(port).sync();
// 监听服务器关闭监听
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
Handler:
@Sharable
public class ProtobufServerHandler extends ChannelInboundHandlerAdapter {
int i = 0;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof CallMessage) {
CallMessage message = (CallMessage) msg;
System.out.println(message.getContent());
i++;
}
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelUnregistered();
System.out.println("断开连接->" + i);
}
}
目前出现的问题是这样:
Client发送数据时如果不加Thread.sleep(1) Server只能接收到64条数据
如果加上就可以全部接收到.但是发送时间肯定会变长.
我想问这个64是在哪设置的,能不能修改.或者说不加sleep接收全部数据,可能是100条,1000条..
谢谢.
客户端代码
finally {
Thread.sleep(1000);
这么写试试,简单来说就是工作已经放到线程中了,但是处理需要时间,但是你都还没有处理好就优雅关闭了,服务端怎么接收