问题
I'm trying to make a client/socket program that involves sending a string from the client (to identify which key should be used) to the server, the server sends back a key in byte form, the client then sends a request for a file in string form, the server sends the requested file to the user which can be decrypted with they key. I understand the cryptology aspects, I'm hung up on how to differentiate between sending bytes, string or a file to and from a server. I understand how to send a single stream (bytes, string or a file), but cannot find a way to send all of these in one stream if that makes any sense? Do I have to create a new stream or socket connection each time I want to send a string, then a new one to send bytes, then a new one to send a file?
Any resources I could perhaps look up? Cheers!
回答1:
Basically, what's sent over a socket connection is a bunch of bytes. This can represent a string, character, or an array of strings..etc.
If you want to send this all in one packet, you need to have designated length for each type of data structure, i.e. the string has a max of 1024 bytes, and the bytes have a max of 512 bytes...etc. Doing this will let you be able to decipher the information on the receiving end.
If you don't have maximum size and don't want to set them then you can take a different approach and send each data structure in its own packet. If you take this route you will need to designate the first byte of the packet to flag the receiver what type of data this is; i.e. 1=bytes, 2=string, 3=array..etc
来源:https://stackoverflow.com/questions/28464762/how-to-send-different-datatypes-over-in-a-socket-connection