2011-09-26 78 views
0

我想使用Java UDP協議將數據包從一臺主機發送到另一臺對等主機。Java UDP數據包讀取失敗

一個主機發送數據,另一個主機讀取數據。然而,相應的讀取保持阻塞,因此不接收數據。我可以看到使用wireshark將發送者數據包發送到正確的目的地,但接收者不會接收它。讀取操作會無限期地阻塞。

請幫忙。 代碼cient:

//CLIENT CLASS 
//Sections ommited.... 
DatagramSocket so = new DatagramSocket(port); 
    protected void send(byte[] buffer,int packetsize){ 
     DatagramPacket p; 
     try { 
      myClient.notifyInform("Sending data to "+inetaddress+" on"+port+"\n"); 
      p=new DatagramPacket(buffer,buffer.length,InetAddress.getByName(inetaddress),port); 
      writeLock.lock(); 
      try{ 
       so.send(p); 
      }finally{ 
       writeLock.unlock(); 
      } 
     } catch (UnknownHostException e) { 
      myClient.perror("Could not connect to peer:"+e.getMessage()+"\n"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      myClient.perror("IOException while sending to peer.\n"); 
      e.printStackTrace(); 
     } 
    } 

    protected DatagramPacket read(){ 
     byte[] buf=new byte[bufsize]; 
     DatagramPacket p=new DatagramPacket(buf,buf.length);//TODO check these values, what should buffer be? just made it psize*10 for now 
     readLock.lock(); 
     try{     
      myClient.notifyInform("receiving data\n"); 
      so.receive(p); 
      this.myclient.notifyInform(String.valueOf(p.getData().length)+"\n"); 
     } catch (IOException e) { 
      myClient.perror("IOException while reading from peer.\n"); 
      e.printStackTrace(); 
     }finally{ 
      readLock.unlock(); 
     } 
     return p; 
    } 

    protected void beginRead() { 
     while(active) { 

      System.out.println("########################"); 
      byte[] data=this.read().getData(); 
      myClient.notifyInform("Receiving data\n"); 
     } 

    } 
    protected void beginSend(){ 
     forkWork(new Runnable(){ 

      @Override 
      public void run() { 

       byte[] sendBuffer=new byte[bufsize]; 
       int cnt; 
       while(callActive){ 
        try{ 
         sourceLock.lock(); 
         cnt=dataSource.read(sendBuffer, 0, bufsize); 
        }finally{ 
         sourceLock.unlock(); 
        } 
        if (cnt >0) { 
         send(sendBuffer, packetsize); 
        } 
       } 
      } 

     }); 

    } 

更新:我犯了一個錯誤,我終於找到了。綁定端口並修復該錯誤後,它現在可以工作。

+1

可以在防火牆塊它?你使用什麼特殊的多播地址? –

+0

不,我將所有防火牆關閉,並且不使用多播。 – Vort3x

+0

兩種簡單的可能性:其他的東西已經綁定了這個端口,或者你在一個Unix/Linux平臺上,試圖綁定一個小於1024而不是根的端口號。 –

回答

3

您需要指定數據報套接字偵聽這樣的端口:

this.so = new DatagramSocket(SOME_NUMBER_HERE); 

,並確保將其發送到相同的端口號在send()方法

1

您的接收DatagramSocket正在偵聽發件人發送的IP:端口嗎?

+0

DatagramSocket沒有指定它。它只讀取發送給它的內容?這是我的socket init代碼:this.so = new DatagramSocket(); – Vort3x

+0

@ Vort3x,如果它沒有監聽任何IP和端口,它將聽不到任何聲音。 –

+0

@ Vort3x恰恰相反。 Javadoc特別說'新的DatagramSocket()將它綁定到任何可用的端口「。所以除非你巧妙地發送到那個端口,否則它將不會收到這些傳輸。這就是綁定和端口號的含義。所以不要這樣做。嘗試'新的DatagramSocket(端口)'; 'port'和你發送的一樣。 – EJP