问题
I am working on a project in which a UDP connection must be used to send an arbitrary file between two unix machines. The main crux of the project is to encode data into byte arrays and send them between the two machines. My original plan was to take byte arrays, form a list out of them, and then serialize them with pickle and send. However, I was just told today by my instructor that using lists and serializing with pickle was not an acceptable solution to the problem. To quote his words:
"You have to encode and decode integer, string, and file objects by yourself, so that you obey the protocol defined in the handout." [this protocol refers to creating segments out of byte arrays, each segment holding 4-byte array for file size, 2-byte array for file name, and 1-byte array for ID flag, as well as a 'payload' byte array which varies in length based on what is being sent.]
I'm not really sure to go with it at this point. I have byte arrays that I need to send to the other machine, but my first two ideas to do so have been disallowed. I can make the byte arrays and the UDP connections (both of which I have tested independently), but sending them is tripping me up. Is there a good solution to my python problem?
回答1:
A byte array in Python is best represented by a str
(a simple string). Your work will probably be to create that byte array according to that protocol specification you got. Take care that it is a str
then, and send it via the network functions for accessing sockets.
To convert a list of integers (bytes) into a str
, use the following:
''.join(chr(c) for c in integer_list)
Or maybe you can build the str
right in the first place (without going via a list of numbers).
来源:https://stackoverflow.com/questions/19637989/python-sending-byte-arrays-via-udp-without-lists-or-pickling