I have the servers connected, but I don't really understand how TCP works well enough to accomplish the task. I want to send the file name before I starting writing the content, but how can I read the file name separately from the content. This was really easy in UDP with socket.receive(packet), but I can't think of a comparable way of doing this with TCP sockets.
我连接了服务器,但我真的不明白TCP如何运行良好来完成任务。我想在开始编写内容之前发送文件名,但是如何从内容中单独读取文件名。这在使用socket.receive(数据包)的UDP中非常简单,但我无法想到使用TCP套接字执行此操作的可比方法。
2 个解决方案
#1
You have two options, depending on the design of your protocol:
您有两种选择,具体取决于协议的设计:
-
send the filename length as a fixed-sized integer, then send the actual filename. The receiver can then read the length first and subsequently read however many bytes it indicates to read the filename.
将文件名长度作为固定大小的整数发送,然后发送实际文件名。然后,接收器可以首先读取长度,然后读取它指示读取文件名的许多字节。
<length><filename><file data>
-
send the filename and then send a unique delimiter, such as a
CRLF
. The receiver can then keep reading until it encounters the delimiter.发送文件名,然后发送一个唯一的分隔符,例如CRLF。接收器然后可以继续读取,直到它遇到分隔符。
<filename><delimiter><file data>
#2
Write the length of the filename using a fixed number of bytes. Then write the filename.
使用固定的字节数写入文件名的长度。然后写入文件名。
On the receiving side, read the length of the filename and then once you know the length, read the filename.
在接收方,读取文件名的长度,然后一旦知道长度,读取文件名。
#1
You have two options, depending on the design of your protocol:
您有两种选择,具体取决于协议的设计:
-
send the filename length as a fixed-sized integer, then send the actual filename. The receiver can then read the length first and subsequently read however many bytes it indicates to read the filename.
将文件名长度作为固定大小的整数发送,然后发送实际文件名。然后,接收器可以首先读取长度,然后读取它指示读取文件名的许多字节。
<length><filename><file data>
-
send the filename and then send a unique delimiter, such as a
CRLF
. The receiver can then keep reading until it encounters the delimiter.发送文件名,然后发送一个唯一的分隔符,例如CRLF。接收器然后可以继续读取,直到它遇到分隔符。
<filename><delimiter><file data>
#2
Write the length of the filename using a fixed number of bytes. Then write the filename.
使用固定的字节数写入文件名的长度。然后写入文件名。
On the receiving side, read the length of the filename and then once you know the length, read the filename.
在接收方,读取文件名的长度,然后一旦知道长度,读取文件名。