[英]Java UDP packet read failing
我正在嘗試使用Java UDP協議將數據包從一台主機發送到另一台對等主機。
一台主機發送數據,而另一台讀取數據。 但是,相應的讀取會一直阻塞,因此不會接收任何數據。 我可以看到發送方數據包使用Wireshark到達了正確的目的地,但是接收方卻不會接聽它。 讀取操作會無限期地阻塞。
請幫忙。 驗證碼:
//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);
}
}
}
});
}
更新:我犯了一個錯誤,我終於找到了。 綁定端口並修復該錯誤后,它現在可以工作。
您需要像這樣指定數據報套接字正在監聽的端口:
this.so = new DatagramSocket(SOME_NUMBER_HERE);
並確保將其發送到send()
方法中的相同端口號
您的接收DatagramSocket是否正在偵聽發送方發送到的IP:端口?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.