client netty 主动发数据_使用Netty在Java中发送连续数据的最佳方法

在设计TCP服务器时,使用Netty并希望在客户端连接后立即开始连续发送XML数据。通常会覆盖`channelConnected`方法进行数据传输。但根据有效的Java原则,不依赖线程调度器,所以希望每个工作线程完成一定量(如1MB)的工作后返回。可以通过在Executor上安排定期任务来写入消息到通道,以实现更高效、可扩展的方案,避免线程阻塞。
摘要由CSDN通过智能技术生成

I'm planning to use Netty to design a TCP Server. When the client connects, I have to immediately start pumping

XML data to the client continuously...for hours/days. Its that simple.

So, I override "channelConnected" method and send data from that method, right?...thats great.

I will be using the following ChannelFactory

ChannelFactory factory =

new NioServerSocketChannelFactory(

Executors.newCachedThreadPool(),

Executors.newCachedThreadPool());

NioServerSocketChannelFactory documentation says

A worker thread performs non-blocking read and write for one or more Channels in a non-blocking mode.

Good.

According to effective Java Item 51: Don't depend on the thread scheduler, I want the worker thread to do a "unit of work" and then finish/return.

So in my case, though I have to send data continuously, I want to send some chunk (lets say 1 MB) and then be done (unit of work completed), so that worker thread can return. Then I'll send another 1 MB.

Below example is from the official guide of Netty HERE.

I guess the question is then, in this scenario, if i had to unconditionally keep sending time to the client, how would I do it, considering

each send as a unit of work.

One way of doing it would be to just put a while loop and do a Thread.Sleep. Any other way?

package org.jboss.netty.example.time;

public class TimeServerHandler extends SimpleChannelHandler {

@Override

public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {

Channel ch = e.getChannel();

ChannelBuffer time = ChannelBuffers.buffer(4);

time.writeInt(System.currentTimeMillis() / 1000);

ChannelFuture f = ch.write(time);

f.addListener(new ChannelFutureListener() {

public void operationComplete(ChannelFuture future) {

Channel ch = future.getChannel();

ch.close();

}

});

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {

e.getCause().printStackTrace();

e.getChannel().close();

}

}

解决方案

Doing a while/sleep would work, but would not be in the Netty super-scalable style. It would be thread-per-connection programming.

Instead, schedule a periodic job on an Executor that writes a message to the channel.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值