Question about how to send images in socket programming? - c++

I've got a couple questions about sending images over.
How do I handle different types of files, jpeg, png, etc.
If the file is large, I ave to use sequence numbers... but I don't know how to stop recving if I do not know the number of sequence numbers.
My knowledge of transfering images / files is next to none. I have never programmed anything like that before. Was hoping to get some tips and tricks =)
Thanks alot.
I am also using QT, if that helps my situation at all.

For images at least, assuming you are using QImage, you can use a QDataStream to convert your QImage to a QByteArray, which can then be written to the QTcpSocket object using write(). It is possible to serialize pretty much any of Qt's data types into a QByteArray using this method.
For general files, the QIODevice (base for QFile, among others) provides read functions such as readAll(), which will read the whole file into a QByteArray ready for you to send.
You will find a number of networking examples included with the Qt distribution. See Qt Assistant -> Contents -> Tutorials and Examples -> Network for more information.

If you use a TCP socket, you need no sequence numbers, because TCP already ensures that data arrive in the same order as they where send. Just send the data, and when done close the connection. Optionally you can use some self-defined type of packet header that gives additional information (e.g. if you want to transmit multiple files over one connection).

Transfer them as you would any other binary data. send(), recv(). Or whichever abstraction Qt provides.

Related

Sending a file via qextserialport

I'm using the qextserialport classes in Qt to implement serial transmissions between devices. Now, I'm required to send a file between devices connected via USB using the serialport. I have used the serialport for various functions in the past weeks but I have no idea where to start implementing this. I thought about reading data event-driven until there is no more data to read, determine the size (number of bytes) of the file before hand and send it together with the data so that it would be clear if data went missing. I also have a correct function that calculates the CCIITT 16 bit checksum so I can use that for checking as well. My question therefore is:
Can someone please send me a link to a site that could help solve my problem and explain to me what would be the most simple and effective way to send a file and receive a file via the qextserialport class in Qt. ANY help would be awsum!
You need a protocol. Simple one could be:
send length of file name as raw binary number, for example 2 bytes in network byte order
(max name length 65535 bytes)
send that many bytes of file name, encoded with UTF-8
send file size as raw binary number, for example 4 bytes in network byte order (max file size 4 gigs)
send that many bytes of file contents
You might want to add info like file date, and checksum. More advanced would be to split file to chunks, so if there is transmission error, you don't have to re-send everything. Etc.
Also, study protocols like Kermit, xmodem, zmodem to see how it's been done in the modem and BBS era. Maybe use an existing protocol like that instead of creating your own.
Note: while you could use QDataStream, it requires reliable channel, so it's not as easy as it may seem at first (requires extra buffering).

Receive audio file via socket

I am trying to receive a file (audio, .CAF) from a socket in C (C++ solution ok as well). I have the socket communication working, having tested it with strings. My problem is I don't know what to supply to the 2nd arg in recv(socket, buffer, buffer_size, 0). What type should I make "buffer"? I basically want to receive an audio file, and will then play it. But don't know how to receive the audio file itself.
Any thoughts?
Thanks,
Robin
Typically, you'll have the audio encoded in some format. For simplicity, let's assume it's Wave format.
One way of doing things would be to encapsulate chunks of the audio (Say, 50 ms chunks) for sending over the network.
However, you can't blindly send data over the network and expect it to work. On your computer, data may be organized one way (little or big endian), and it could be organized in the opposite way on the other computer.
In that case, the client will get data that he interprets as being completely different than what you intended. So, you'll need to properly serialize it somehow.
Once you properly serialize the data though (or not, if both computers use the same endianess!), you can just send() it and rcev() it, then just pass it off to a decoder to deal with.
I'd love to offer more information, but that's about the extent of my knowledge on the subject. It really depends on what exactly you're doing, so it's hard to give any more information without some more specifics as to what you're doing (with regards to audio format, for one).
Some more information:
http://en.wikipedia.org/wiki/Serialization
http://en.wikipedia.org/wiki/Endianness
Edit: As pointed out in the comments of this answer, you should probably not worry about serialization at all if you're using a standard format. Just pass it over the network in chunks that are usable by your decoder (Send a frame at a time, for example) then decode those individual frames (or possibly multiple frames) on the client side.
buffer is going to be a pointer to an array you've allocated to store the data the comes across the wire.
It depends on the socket library you're using, but usually it expects void* (which is just a generic pointer type).
You might do something like this:
uint8[1000] myBuffer;
recv(sock,myBuffer,1000,0);
It gets tricky because this only gives you enough room for 8,000bytes, which might not be enough to hold your audio file, so you'll have to handle multiple recv() calls until you get the entire audio file.

About Google's protobuf

I know it can be used to send/receive structured object from file,
but can it be used to send/receive sequences of structured object from a socket?
http://code.google.com/p/protobuf/
Protocol Buffers is a structured data serialization (and de-serialization) framework. It is only concerned with encoding a selection of pre-defined data types into a data stream. What you do with that stream is up to you. To quote the wiki:
If you want to write multiple messages
to a single file or stream, it is up
to you to keep track of where one
message ends and the next begins. The
Protocol Buffer wire format is not
self-delimiting, so protocol buffer
parsers cannot determine where a
message ends on their own. The easiest
way to solve this problem is to write
the size of each message before you
write the message itself. When you
read the messages back in, you read
the size, then read the bytes into a
separate buffer, then parse from that
buffer.
So yes, you could use it to send/receive multiple objects via a socket but you have to do some extra work to differentiate each object stream.
I'm not familiar with protobuf, but the documentation says you can create a FileInputStream (which can then be used to create a CodedInputStream) using a file descriptor. If you're on a system that supports BSD sockets, you should presumably be able to give it a socket file descriptor rather than an ordinary one.
Protocol Buffers does not handle any surrounding network/file I/O operations. You might want to consider using Thrift, which includes socket communication libraries and server libraries with the serialization/deserialization.

Tips / Examples on sending an Image file (jpeg, png) over socket programming?

I've heard that we can somehow send an image file with binary over a socket...
But I have no idea on how to convert an image file into binary or how to even think of sending it over a socket...
Was hoping if someone could post a simple example? or point me in the right direction :) I am also using QT for just my gui, but not using QT socket programming.
Thanks so much :D I really appreciate it
Question # djc:
How would you get the directory path for an image, and somehow use the send command on that image? I'm basically using C++. But this is also a question I've had for awhile.
Any image files you have are already binary. You can just send them over the socket.
You will need to know, or have the user tell you, a path that will find the image file.
Once you have that, then you logically open the file, read it into a buffer, and then write that buffer over the socket, and finally close the file (always close what you open and free what you allocate). However, there are details to be sorted - like how does the receiving end know that the data that follows is an image and how big it is (so it knows when you've sent it all). Your protocol will, presumably, define a bit pattern (one or two bytes) that identifies the message as an image, and then probably use four bytes to specify the size of the image, followed by the correct number of bytes. You can find the size of a file using the POSIX-based stat() system call. Alternatively, you can send a series of packets containing parts of the image (again with a type - this time, of type 'image packet' instead of 'image') plus the length of the packet (which might only be a 16-bit unsigned integer, for a maximum size of 65535 bytes), plus an 'end image packet' for the last segment. This is perhaps easier for the sender; it is easy for the receiver if the data goes direct to file, but messy if the receiver needs the image in memory.

Sending large chunks of data over Boost TCP?

I have to send mesh data via TCP from one computer to another... These meshes can be rather large. I'm having a tough time thinking about what the best way to send them over TCP will be as I don't know much about network programming.
Here is my basic class structure that I need to fit into buffers to be sent via TCP:
class PrimitiveCollection
{
std::vector<Primitive*> primitives;
};
class Primitive
{
PRIMTYPES primType; // PRIMTYPES is just an enum with values for fan, strip, etc...
unsigned int numVertices;
std::vector<Vertex*> vertices;
};
class Vertex
{
float X;
float Y;
float Z;
float XNormal;
float ZNormal;
};
I'm using the Boost library and their TCP stuff... it is fairly easy to use. You can just fill a buffer and send it off via TCP.
However, of course this buffer can only be so big and I could have up to 2 megabytes of data to send.
So what would be the best way to get the above class structure into the buffers needed and sent over the network? I would need to deserialize on the recieving end also.
Any guidance in this would be much appreciated.
EDIT: I realize after reading this again that this really is a more general problem that is not specific to Boost... Its more of a problem of chunking the data and sending it. However I'm still interested to see if Boost has anything that can abstract this away somewhat.
Have you tried it with Boost's TCP? I don't see why 2MB would be an issue to transfer. I'm assuming we're talking about a LAN running at 100mbps or 1gbps, a computer with plenty of RAM, and don't have to have > 20ms response times? If your goal is to just get all 2MB from one computer to another, just send it, TCP will handle chunking it up for you.
I have a TCP latency checking tool that I wrote with Boost, that tries to send buffers of various sizes, I routinely check up to 20MB and those seem to get through without problems.
I guess what I'm trying to say is don't spend your time developing a solution unless you know you have a problem :-)
--------- Solution Implementation --------
Now that I've had a few minutes on my hands, I went through and made a quick implementation of what you were talking about: https://github.com/teeks99/data-chunker There are three big parts:
The serializer/deserializer, boost has its own, but its not much better than rolling your own, so I did.
Sender - Connects to the receiver over TCP and sends the data
Receiver - Waits for connections from the sender and unpacks the data it receives.
I've included the .exe(s) in the zip, run Sender.exe/Receiver.exe --help to see the options, or just look at main.
More detailed explanation:
Open two command prompts, and go to DataChunker\Debug in both of them.
Run Receiver.exe in one of the
Run Sender.exe in the other one (possible on a different computer, in which case add --remote-host=IP.ADD.RE.SS after the executable name, if you want to try sending more than once and --num-sends=10 to send ten times).
Looking at the code, you can see what's going on, creating the receiver and sender ends of the TCP socket in the respecitve main() functions. The sender creates a new PrimitiveCollection and fills it in with some example data, then serializes and sends it...the receiver deserializes the data into a new PrimitiveCollection, at which point the primitive collection could be used by someone else, but I just wrote to the console that it was done.
Edit: Moved the example to github.
Without anything fancy, from what I remember in my network class:
Send a message to the receiver asking what size data chunks it can handle
Take a minimum of that and your own sending capabilities, then reply saying:
What size you'll be sending, how many you'll be sending
After you get that, just send each chunk. You'll want to wait for an "Ok" reply, so you know you're not wasting time sending to a client that's not there. This is also a good time for the client to send a "I'm canceling" message instead of "Ok".
Send until all packets have been replied with an "Ok"
The data is transfered.
This works because TCP guarantees in-order delivery. UDP would require packet numbers (for ordering).
Compression is the same, except you're sending compressed data. (Data is data, it all depends on how you interpret it). Just make sure you communicate how the data is compressed :)
As for examples, all I could dig up was this page and this old question. I think what you're doing would work well in tandem with Boost.Serialization.
I would like to add one more point to consider - setting TCP socket buffer size in order to increase socket performance to some extent.
There is an utility Iperf that let test speed of exchange over the TCP socket. I ran on Windows a few tests in a 100 Mbs LAN. With the 8Kb default TCP window size the speed is 89 Mbits/sec and with 64Kb TCP window size the speed is 94 Mbits/sec.
In addition to how to chunk and deliver the data, another issue you should consider is platform differences. If the two computers are the same architecture, and the code running on both sides is the same version of the same compiler, then you should, probably, be able to just dump the raw memory structure across the network and have it work on the other side. If everything isn't the same, though, you can run into problems with endianness, structure padding, field alignment, etc.
In general, it's good to define a network format for the data separately from your in-memory representation. That format can be binary, in which case numeric values should be converted to standard forms (mainly, changing endianness to "network order", which is big-endian), or it can be textual. Many network protocols opt for text because it eliminates a lot of formatting issues and because it makes debugging easier. Personally, I really like JSON. It's not too verbose, there are good libraries available for every programming language, and it's really easy for humans to read and understand.
One of the key issues to consider when defining your network protocol is how the receiver knows when it has received all of the data. There are two basic approaches. First, you can send an explicit size at the beginning of the message, then the receiver knows to keep reading until it's gotten that many bytes. The other is to use some sort of an end-of-message delimiter. The latter has the advantage that you don't have to know in advance how many bytes you're sending, but the disadvantage that you have to figure out how to make sure the the end-of-message delimiter can't appear in the message.
Once you decide how the data should be structured as it's flowing across the network, then you should figure out a way to convert the internal representation to that format, ideally in a "streaming" way, so you can loop through your data structure, converting each piece of it to network format and writing it to the network socket.
On the receiving side, you just reverse the process, decoding the network format to the appropriate in-memory format.
My recommendation for your case is to use JSON. 2 MB is not a lot of data, so the overhead of generating and parsing won't be large, and you can easily represent your data structure directly in JSON. The resulting text will be self-delimiting, human-readable, easy to stream, and easy to parse back into memory on the destination side.