2012-08-17 42 views
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方法結束並且只有一個筆劃。不幸的是,我不知道,並希望得到一個提示。

回答

0

您需要儘快從channelBound返回,因爲您通過在其中運行所有代碼來阻止Netty的I/O線程。

你應該(在Netty的圖書館什麼的等價物,如果存在的話)使用Executor執行您的長時間運行的代碼(在這種情況下,您的dataReader循環),這樣的Netty的一個線程不會阻止等待你的代碼完成。