[英]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.