我正在用 java 编写一个网络程序,我想发送一些数据包到 255.255.255.255,但它失败了,即使我将它们发送到 192.168.1.255,根据 ifconfig 命令的输出,它是广播地址。 但是当我将它们发送到我伙伴的 IP 时,它工作正常。 这是我的程序的代码: 我使用 Dat ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
使用Java,我试图通过DatagramSocket发送一些文件数据。 我需要读取1000字节的文件块并将其作为数据包发送出去。 我的代码:
我在将字节数组写回到文件时遇到问题。 请在下面查看我的代码。
客户端/发件人:
byte[] data = new byte[1000];
ByteBuffer b = ByteBuffer.wrap(data);
DatagramPacket pkt;
File file = new File(sourceFile);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
CRC32 crc = new CRC32();
while(true){
b.clear();
b.putLong(0); // I need to put the checksum at the beginning for easy retrieval
bytesRead = bis.read(data);
if(bytesRead==-1) { break; }
crc.reset();
crc.update(data, 8, data.length-8);
long chksum = crc.getValue();
b.rewind();
b.putLong(chksum);
pkt = new DatagramPacket(data, 1000, addr); // addr is valid, works fine
sk.send(pkt);
}
bis.close();
fis.close();
服务器/接收器:
DatagramSocket sk = new DatagramSocket(port);
File destfile = new File("hello.txt");
FileOutputStream fos = new FileOutputStream(destfile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintStream ps = new PrintStream(fos);
byte[] data = new byte[1000];
DatagramPacket pkt = new DatagramPacket(data, data.length);
ByteBuffer b = ByteBuffer.wrap(data);
CRC32 crc = new CRC32();
while(true) {
pkt.setLength(data.length);
sk.receive(pkt);
b.rewind();
// compare checksum, print error if checksum is different
// if checksum is the same:
bos.write(data); // Where the problem seems to be occurring.
// send acknowledgement packet.
}
bos.close();
fos.close();
在这里,我主要遇到写回文件的问题。 带有一个小的文本文件,上面写着“ Hello World!
,我得到一个奇怪的输出,说vˇ]rld!
。 同样,输入文件只有12个字节,但是接收者创建的文件是1KB。
我认为我的问题是处理字节缓冲区-我编写了一个程序,该程序使用文件流和缓冲流复制文件,效果很好。 但是我对流在这种情况下的工作方式感到困惑,我将非常感谢您的帮助。 谢谢!
在发件人的data []中,您将覆盖crc从文件中读取的文本! 您必须阅读很长一段时间后的内容。 在发件人中更正此错误时,它的工作原理是:
//int bytesRead = bis.read(data); --old code
int bytesRead=bis.read(data,8,data.length-8);
此外,您发送1000字节,因此将接收1000字节,该字节将进入destfile。
顺便说一句:您不检查服务器中的crc。...为什么要发送它?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.