TCP 文件传输问题
I. 简介
我正在打开并读取一个文件,在读取时通过 TCP 套接字发送数据块。
发送者代码
byte[] buffer = new byte[16384];
while ((in.read(buffer)) > 0)
{
SendProtocol(new FileTransfer(sender, receiver, buffer);
}
接收者代码
if(o instanceOf FileTransfer)
FileTransfer tf = (FileTransfer) o;
out.write(tf.getData);
}
II.问题
通过 TCP 套接字发送协议后,我查看了正在发送的字节。他们都是独一无二的。但在接收方,接收到的字节只是一遍又一遍相同的 byte[]。
三.例子
SENDER BYTES
[3, 3, 5, -44, 4, 3]
[99, -3, 5, -44, 7, 3]
[-11, 3, 5, -44, 4, 7]
[10, 6, 5, -44, 4, 66]
RECEIVER BYTES
[3, 3, 5, -44, 4, 3]
[3, 3, 5, -44, 4, 3]
[3, 3, 5, -44, 4, 3]
[3, 3, 5, -44, 4, 3]
I. Introduction
I am opening and reading from a file, sending chunks of data through a TCP socket as I read.
SENDER CODE
byte[] buffer = new byte[16384];
while ((in.read(buffer)) > 0)
{
SendProtocol(new FileTransfer(sender, receiver, buffer);
}
RECEIVER CODE
if(o instanceOf FileTransfer)
FileTransfer tf = (FileTransfer) o;
out.write(tf.getData);
}
II. Problem
After I send the protocol through the TCP socket, I view the bytes being sent over. They are all unique. BUT at the receiver side, the bytes received is just the same byte[] over and over.
III. Example
SENDER BYTES
[3, 3, 5, -44, 4, 3]
[99, -3, 5, -44, 7, 3]
[-11, 3, 5, -44, 4, 7]
[10, 6, 5, -44, 4, 66]
RECEIVER BYTES
[3, 3, 5, -44, 4, 3]
[3, 3, 5, -44, 4, 3]
[3, 3, 5, -44, 4, 3]
[3, 3, 5, -44, 4, 3]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您遇到的一个问题是您没有检查收到的字节数。可能您几乎每次通过环回都会获得完整的缓冲区,但您不太可能通过真实网络获得此缓冲区。您必须记录读入缓冲区的字节数并仅使用该数量。
One problem you have is that you don't check how many bytes you recieved. It may be that you get a full buffer almost every time over loopback, but you are unlikely to get this over a real network. You have to record how many bytes were read into the buffer and use only that amount.
也许我所做的这个测试示例清楚地表明了您错过了什么:
Maybe this test example I did makes it clear what you have missed:
写入所有信息后使用
out.flush()
。use
out.flush()
after writing all the information.什么是 FileTransfer,它的构造函数是否复制缓冲区?它的操作是异步的吗?它的缓冲区可能在复制到 TCP 套接字之前被循环重新填充。即,您不断将指向同一缓冲区的指针排队,然后在循环中覆盖该缓冲区。
使 FileTransfer 承担缓冲区参数的所有权,并在发送时将其删除。然后为循环中的每次行程分配一个新的,并将其交给 FileTransfer。
What's FileTransfer, and does its constructor copy the buffer? Is its operation asynchronous? It could be that its buffer gets refilled by the loop before it has been copied to the TCP socket. I.e., you keep queueing up pointers to the same buffer, which you then overwrite in the loop.
Make FileTransfer assume ownership of the buffer parameter, deleting it when sent. Then allocate a fresh one for each trip through the loop and hand it off to the FileTransfer.