gpt4 book ai didi

Java UDP数据包读取失败

转载 作者:行者123 更新时间:2023-12-01 19:13:47 26 4
gpt4 key购买 nike

我正在尝试使用 java UDP 协议(protocol)将数据包从一台主机发送到另一台对等主机。

一台主机发送数据,另一台主机读取数据。然而,相应的读取保持阻塞,因此没有接收到数据。我可以使用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);
}
}
}

});

}

更新:我犯了一个错误,我终于找到了。绑定(bind)端口并修复该错误后,它现在可以工作了。

最佳答案

您需要指定数据报套接字正在监听的端口,如下所示:

 this.so = new DatagramSocket(SOME_NUMBER_HERE);

并确保将其发送到 send() 方法中的相同端口号

关于Java UDP数据包读取失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7552612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com