gpt4 book ai didi

Java通过套接字发送字节[] ...读取的长度错误

转载 作者:行者123 更新时间:2023-12-03 11:52:20 25 4
gpt4 key购买 nike

对于我的家庭作业,我有一个节点网络,它们相互传递消息。每个节点都连接到一定数量的其他节点(我使用 4 个进行测试)。每个链接都有一个权重,所有节点都计算了它们希望如何发送消息的最短路径。发送的每个数据包都由消息协议(protocol)(硬编码的 int)、一个整数(表示有多少消息通过发送节点)和数据包的路由路径组成。

每个节点的每个链接都有一个线程。每个 Link 中都有一个 Activity 的 Socket。通过在消息的开头添加一个 4 字节的 int 来发送数据包,以告知消息的长度。

一切正常,直到我强调网络。对于我的测试,有 10 个节点,我让其中 5 个在没有 Thread.sleep() 的简单 while() 循环中发送 10000 个数据包。无一异常(exception),在 if(a!=len) 语句执行过程中的某个时刻总会出现错误。

如果我能澄清任何事情,请告诉我。提前致谢!这是代码(来自链接线程;从节点本身调用 send() 和 forward()):

protected void listen(){
byte[] b;
int len;
try{
DataInputStream in = new DataInputStream(sock.getInputStream());
while(true){
len = in.readInt();
b = new byte[len];
int a = in.read(b,0,len);
if(a!=len){
System.out.println("ERROR: " + a + "!=" + len);
throw new SocketException(); //may have to fix...this will happen when message is corrupt/incomplete
}
Message m = new Message(b);
int p = m.getProtocol();
switch (p){
case CDNP.PACKET:
owner.incrementTracker();
System.out.print("\n# INCOMMING TRACKER: " + m.getTracker() + "\n>>> ");
owner.forward(m);
}
}
}catch (IOException e){
e.printStackTrace();
}
}

public void send(int tracker){
String[] message = { Conv.is(CDNP.PACKET), Conv.is(tracker), owner.getMST().toString() };
Message m = new Message(message);
forward(m);
}

public synchronized void forward(Message m){
try{
OutputStream out = sock.getOutputStream();
//convert length to byte array of length 4
ByteBuffer bb = ByteBuffer.allocate(4+m.getLength());
bb.putInt(m.getLength());
bb.put(m.getBytes());
out.write(bb.array());
out.flush();
}catch (UnknownHostException e){
System.out.println("ERROR: Could not send to Router at " + sock.getRemoteSocketAddress().toString());
return;
}catch (IOException e1){

}
}

最佳答案

int a = in.read(b,0,len);
if(a!=len){

那是行不通的。 InputStream 可能不会读取您想要的所有字节,它可能只读取现在可用的内容,并在不阻塞的情况下返回那么多。

quote the Javadocs (强调我的):

Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer.



您需要继续循环读取,直到获得所需的所有数据(或流完成)。

或者,由于您使用的是 DataInputStream,您也可以使用
in.readFully(b, 0, len);

总是准确地读取 len字节(阻塞直到那些到达,当没有足够的数据时抛出异常)。

关于Java通过套接字发送字节[] ...读取的长度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9271868/

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