1
使用Netty 3.5.3我正在實現一個UDP服務器,它必須連續發送小數據包而無需任何請求 - 響應通信。在論壇的任何地方,我發現提示最好的做法是重寫SimpleChannelHandler的channelBound方法。Netty Framework:UDP發送海量數據
private static class MyHandler extends SimpleChannelHandler {
private TargetDataReader dataReader = new TargetDataReader();
private InetSocketAddress remoteAddress;
private long sleep;
/**
* @param host
* @param port
*/
public MyHandler(String host, int port, long sleep) {
super();
this.remoteAddress = new InetSocketAddress(host, port);
this.sleep = sleep;
}
/*
* {@inheritDoc}
*/
@Override
public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
Channel ch = e.getChannel();
int cnt = 0;
long start = System.currentTimeMillis();
byte[] targetData;
while ((targetData = dataReader.nextData()) != null) {
ChannelBuffer tdBuf = ChannelBuffers.wrappedBuffer(targetData);
++cnt;
ChannelFuture cf = ch.write(tdBuf, this.remoteAddress);
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("Server - record sent "
+ (future.isSuccess() ? "successfully" : "failed"));
}
});
cf.await(30);
if (sleep > 0)
Thread.sleep(sleep);
System.out.println("Server - written records " + cnt);
}
long duration = System.currentTimeMillis() - start;
System.out.println("Server - duration=" + duration + ", cnt=" + cnt + ", records/sec="
+ String.format("%f", ((double) cnt)/duration * 1000));
}
乍一看,它似乎工作。但是更深入地看到,我意識到接收客戶端只能獲得大約50%的數據包。此外,我認爲這是實際的問題,當調用時,服務器並不真正發送數據包ChannelFuture cf = ch.write(tdBuf,this.remoteAddress);,但是直到channelBound方法結束並且只有一個筆劃。不幸的是,我不知道,並希望得到一個提示。