Receive audio file via socket - c++

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.

Related

reassembly of tcp packet

I'm parsing a file with lots of tcp packets which i need to parse. The problem is that they get segmented and i can't find any indication when and where they do so. No flags or anything else indicates, that the middle of current packet may contain the beginning of the next one. The protocol above tcp is FIX(used in online trading) but i'd like for my code to be able to work with any protocols(or at least understand which is protocol is it).
I'm writing code in C++ and can't use any additional libraries.
So, how do i figure out what is the protocol above tcp and where it gets segmented ?
You can't. TCP/IP is conceptually a stream, not a sequence of messages (the fact that it is ultimately implemented as a sequence of packets is irrelevant). When you write a sequence of bytes to a TCP/IP stream, that sequence is added to the stream; it is not treated as a message which should maintain its own identity. No notion of message begin/end is transmitted along with the stream, unless you do so yourself in your own protocol.
If you find this hard to believe, consider how it works for files: if you write a sequence of bytes to a file, that sequence does not somehow become a record that you can later identify and retrieve. If you want that kind of structure you have to add it yourself. The same is true for TCP/IP.
The transport packets used to implement TCP/IP have no relation to the data blocks you specify with your API calls; they are merely a way to implement the TCP/IP stream. For some use cases there may appear to be a mapping, but this is accidental.
The only way to split a TCP/IP stream back into separate messages is by using knowledge of the protocol running on top of TCP/IP. In your case this is FIX. I assume you know how that works; you can use that knowledge to correctly split the FIX data back into its original messages. A generic TCP/IP message splitter cannot be made.
As I can see your problem is to separate TCP packets. To solve it you can relay on length of payload (this answer) and checksum. If checksum is correct for data with specified length, than your packet is correct, if no - you need seek in thee previous part for start of the packet or drop this part of data. At least this approach will help you to find point where dada was segmented.
For more precise answer it will be better to see little part of data.
But main your problem is segmentation of packets. For better performance you should try to exclude this problem (maybe change network card to Intel).

Question about how to send images in socket programming?

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.

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.

Question about file transfer for socket programming

Is there a good method on how to transfer a file from say... a client to a server?
Probably just images, but my professor was asking for any type of files.
I've looked around and am a little confused as to the general idea.
So if we have a large file, we can split that file into segments...? Then send each segment off to the server.
Should I also use a while loop to receive all the files / segments on the server side? Also, how will my server know if all the segments were received without previously knowing how many segments there are?
I was looking on the Cplusplus website and found that there is like a binary transfer of files...
Thanks for all the help =)
If you are using TCP:
You are right, there is no way to "know" how much data you will be receiving. This gives you a few options:
1) Before transmitting the image data, first send the number of bytes to be expected. So your first 4 bytes might be the 4-byte integer "4096". Then your client can read the first 4 bytes, "know" that it is expecting 4096 bytes, and then malloc(4096) so it can expect the rest. Then, your server can send() 4096 bytes worth of image data.
When you do this, be aware that you might have to recv() multiple times - for one reason or another, you might not have received all 4096 bytes. So you will need to check the return value of recv() to make sure you have gotten everything.
2) If you are just sending one file, you could just have your receiver read it. And it can keep recv()ing from the socket until the server closes the connection. This is a bit harder - you will have to keep track of how much you have received, and then if your buffer is full, you will have to reallocate it. I don't recommend this method, but it would technically accomplish the task.
If you are using UDP:
This means that you don't have reliable transfer. So packets might be dropped. They might also arrive out of order. So if you are going to use UDP, you must fragment your data into little segments. Both the sender and receiver must have agreement on how large a segment is (100 bytes? 1000 bytes?)
Not only that, but you must also transmit a sequence number with each packet - that is, label each packet #1, #2, etc. Because your client must be able to tell: if any packets are missing (you receive packets 1, 2 and 4 - and are thus missing #3) and to make sure they are in order (you receive 3, 2, then 1 - but when you save them to the file, you must make sure the packets are saved in the correct order, 1, 2, then 3).
So for your assignment, well, it will depend on what protocol you have to/are allowed to use.
If you use a UDP-based transfer protocol, you will have to break the file up into chunks for network transmission. You'll also have to reassemble them in the correct order on the receiving end and verify the results. If you use a TCP-based transfer protocol, all of this will be taken care of under the hood.
You should consult Beej's Guide to Network Programming for how best to send and receive data and use sockets in general. It explains most of the things about which you are asking.
There are many ways of transferring files. If your transferring files in a lossless manor, then your basically going to divide the file into chunks. Tag each chunk with a sequence number. Send the chunks to the other side and reconstitute the file. Stream oriented protocols are simpler since packets will be retransmitted if lost. If your using an unreliable protocol, then you will need to retransmit missing packets and resequenced chunks which are not in the correct order.
If lossy transfer is acceptable (like transferring video or on-line game data), then use an unreliable protocol. Lossy transfer is simpler because you don't have to retransmit missing chunks. All you need to do is make sure the chunks are processed in the proper sequence.
Many protocols send a terminator packet to indicate the end of transmission. You could use this strategy if you don't want to send the number of chunks to the other side before transmission.