I am trying to use some socket network programming in C++. I am trying to send the text "Hello World!" to a server using the C++ send() function. At first, I set the buffer to the size of 13 since "Hello World!" altogether is 12 characters (you have to make it one more than the character count). The send function only sends the characters to the server if I send it about 7 times. And when it does finally come to the server it looks like this:
"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!"
Now here is the funny part. The "Hello World!" sentence sends immediately if I set the buffer size to 256 (char buffer[256];). When it comes to the server like that though, it shows "Hello World!" with a whole bunch of space after the two words. Why is this happening and if possible, how can I fix it? Please let me know.
Thanks
When you call read (or receive) with your buffer to read from the socket, an integer value is returned that specifies the number of bytes read. You should only take that much from the buffer. The rest is irrelevant:
int count = read(...);
// buffer[0 .. count - 1] contains the appropriate data.
Nagle's algorithm usually is turned on by default. This will combine several small packets into one. Turning Nagle's algorithm off will allow small packets to be sent immediately.
Buffers exist to store data until you are ready to send it. You have a send buffer size of 256. Until 256 characters are transmitted through the buffer, your data won't be sent to the other side. You can fix this by calling a flush method on your buffer when you know you are ready to send.
To be clear, you are buffering internally, then the OS (or library) is buffering again when you call send() and pass some data.
If you get more specific with what library you are using and maybe include a code snippet, we can probably find the right buffer flush function to send you on your way with.
Alternatively, if you are in *nix, just turn off Nagle's algorithm so that the OS won't buffer your small packets. Or, when you set up you socket, make sure to use the TCP_NODELAY option
Assuming this is a SOCK_STREAM socket, the important thing to be aware of is that the underlying TCP protocol does not maintain any segment boundaries. That is, when you call send() multiple times, all of the data you sent may very easily be returned by a single recv() call at the other end. Or, the data sent in one send() call may be returned in multiple recv()s at the other end, e.g. if some packets got delayed due to network congestion. This is fundamental to the design of TCP, and your application must be designed accordingly.
Also, as noted by Mehrdad, the recv() call returns the number of bytes that were read off the wire. Anything after that point in the buffer is garbage, and the data is not zero-terminated.
A SOCK_DGRAM socket uses UDP underneath, which is entirely packet-oriented, as opposed to stream-oriented like TCP. However, UDP does not guarantee reliability (the U stands for Unreliable), so you have to handle lost, duplicated, out-of-order etc. packets yourself. This is a lot harder than stream-oriented I/O.
Socket programming is tedious, error prone and non portable. Start using libraries like Boost or ACE that shield you from the low level C APIs and provide you with platform independent abstractions.
Related
I'm working on a networking project. I have to know, if I send a data from a client to server listener, can listener handle this data with 2 or more callbacks (TCP-blocking)? Namely I've sent "Hello World", can server listener (TCP-blocking) handle this receive like 1"Hello" 2"World" or 1"Hell" 2"o World" etc.? If this is posibble I'm going to create a packet handler for my TCP data packets. Thanks!
EDIT: (more desciption), Is this posibble (TCP-blocking)?
Client says "Hello world"
Server reads "Hello" in first callback "recv();" (recv(); function gives "Hello" output)
Server reads " world" in second callback "recv();" (recv(); function gives " world" output)
Yes, this is absolutely possible. In this particular case, it's quite unlikely, but if your packet is a bit larger than 12 bytes - say several hundred or a few thousand bytes, it will almost certainly get split up if you send it somewhere further than your local network.
It should be noted that you can also get the opposite problem - the sending side sends two individual "packets", and the receiving side receives only one lump of data. Bear in mind that TCP is a stream protocol, not a packet protocol - packets only exist as part of the underlying protocol stack, and they can be split and merged as the network sees fit. All that you are guaranteed is that the data you receive is in the correct order, and that the checksum for the lump of data was correct.
If you know exactly how long each part of data is (for e.g. "Hello" is 5 characters long), you can block on reading in first callback and then on second (with separate calls to recv()).
Or if you know how these parts will be separated (in your case it's space), then you can recv() in first callback by 1 byte and then, when you receive your separator, switch to receive in second callback.
Or maybe you can differentiate them using your special protocol (if you have one).
But still, I'm not sure in which layer do you want these packages to be interpreted separately.
EDIT!
Just read that read will block until the buffer is full. How on earth to I receive smaller packets with out having to send 1MB (my max buffer length) each time? What If I want to send arbitrarily length messages?
In Java you seem to be able to just send a char array without any worries. But in C++ with the boost sockets I seem to either have to keep calling socket.read(...) until I think I have everything or send my full buffer length of data which seems wasteful.
Old original question for context.
Yet again boost sockets has me completely stumped. I am using
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket; I
used the boost SSL example for guidance but I have dedicated a thread
to it rather than having the async calls.
The first socket.read_some(...) of the socket is fine and it reads
all the bytes. After that it reads 1 byte and then all the rest on the
next socket.read_some(...) which had me really confused. I then
noticed that read_some typically has this behaviour. So I moved to
boost::asio::read as socket does have a member function read which
surprised me. However noticed boost::asio has a read function that
takes a socket and buffer. However it is permanently blocking.
//read blocking data method
//now
bytesread = boost::asio::read(socket,buffer(readBuffer, max_length)); << perminatly blocks never seems to read.
//was
//bytesread = socket.read_some(buffer(readBuffer, max_length)); << after the 1st read it will always read one byte and need another
socket.read_some(...) call to read the rest.
What do I need to do make boost::asio::read(...) work?
note .. I have used wireshark to make sure that the server is not
sending the data broken up. The server is not faulty.
Read with read_some() in a loop merging the buffers until you get a complete application message. Assume you can get back anything between 1 byte and full length of your buffer.
Regarding "knowing when you are finished" - that goes into your application level protocol, which could use either delimited messages, fixed length messages, fixed length headers that tell payload length, etc.
I am trying to send a message over a TCP socket at a regular interval (every second). Sometimes the full message will not be sent or two-four messages will be stacked and sent at once. I have if statements for if the return value is 0 or < 0, but those are never true. I tried the obvious approach of checking the exact return value of send() to see if less or more bytes were sent. It just returns the number that I specify in the parameter to send (which makes sense if send blocks until it sends that much), even if less bytes are sent. So is there an accurate way to say "was the right size packet sent? no? - do something"?
TCP provides a reliable stream of bytes, there's no message boundary. If you need to know the length of the message you have to build this into the protocol, eg: send every message with a 2 byte header which specifies the message length.
There's no such facility with TCP. It's up to the in-kernel network stack how to slice TCP stream into packets. Having said that you can set TCP_NODELAY option on your socket to disable Nagle algorithm.
If I am understanding you right, sometimes you send two or more packets and they are received as one on the distant end.
This is the nature of TCP/IP. You cannot guarantee the packets will arrive as distinct, just that they will arrive in order and reliably.
Not sure what platform you are using or what syntax you are using (streams, FILE objects or file descriptors; some code would clarify this) but you may need to do an explicit flush operation after you write each message to force the kernel. I generally use C-style file descriptors and it is usually sufficient to call fflush on the descriptors to make whatever I've queued up go out immediately.
I've encountered an issue when sending large segments of data through a TCP socket, having spend about 3 days trying to pick apart the issue and failing I decided it was best to turn here for help / advice.
My Project
I've written a basic HTTP server which (slightly irrelevant) can run lua scripts to output pages. This all works perfectly fine under Windows (32 bit).
The Problem
When sending medium/large files (anything from roughly 8000 bytes and above appears to have issues) over the TCP socket on Ubuntu Linux(64bit), they appear to cut out at different lengths (the result displayed in the browser is a value between 8000 and 10200 bytes. When I check the return value of the send function it's exactly 9926 bytes every time the send ends. No error.
Smaller files send absolutely fine, and there are no issues under windows. Going on this information I thought it could be a buffer size issues, so I did
cat /proc/sys/net/ipv4/tcp_mem
which outputted 188416 192512 196608
those numbers are far above 9926 so I assume that isn't the problem.
I'm using CSimpleSockets as a socket library, I haven't had any issues before. In case the issue is inside of this library the code I dug around for what the send function used under unix is:
#define SEND(a,b,c,d) send(a, (const int8 *)b, c, d)
send(socket, buffer, bytestosend, 0);
buffer gets cast from a const char * to const unsigned char* to const int8 * before getting passed to the OS to be sent.
OK, I think that covers everything I checked. If you need any more information or I've missed anything glaringly obvious I'll do my best to provide. Thanks for your help!
Your problem is that send does not guarantee to send the amount of data passed to it.
It has internal buffers that can fill, socket parameters that affect buffers, etc. You need to note how many bytes were sent, wait for a few milliseconds (for the send to move data over the wire and empty the buffer), then send the remaining data. There is no automatic way to do this and you'll need to write a bit of logic which advances your buffer by the amount of bytes that were actually sent.
Are you using blocking or non-blocking sockets? If you're using non-blocking sockets, you must (and with blocking sockets, you should) check for a short send (one where the return value is fewer than the number of bytes you meant to send).
I have a problem - when I'm trying to send huge amounts of data through posix sockets ( doesn't matter if it's files or some data ) at some point I don't receive what I expect - I used wireshark to determine what's causing errors, and I found out, that exactly at the point my app breaks there are packets marked red saying "zero window" or "window full" sent in both directions.
The result is, that the application layer does not get a piece of data sent by send() function. It gets the next part though...
Am I doing something wrong?
EDIT:
Lets say I want to send 19232 pieces of data 1024 bytes each - at some random point ( or not at all ) instead of the 9344th packet I get the 9345th. And I didn't implement any retransmission protocol because I thought TCP does it for me.
Zero Window / Window Full is an indication that one end of the TCP connection cannot recieve any more data, until its client application reads some of the data is has already recieved. In other words, it is one side of the connection telling the other side "do not send any more data until I tell you otherwise".
TCP does handle retransmissions. Your problem is likely that:
The application on the recieving side is not reading data fast enough.
This causes the recieving TCP to report Window Full to the sending TCP.
This in turn causes send() on the sending TCP side to return either 0 (no bytes written), or -1 with errno set to EWOULDBLOCK.
Your sending application is NOT detecting this case, and is assuming that send() sent all the data you asked to send.
This causes the data to get lost. You need to fix the sending side so that it handles send() failing, including returning a value smaller than the number of bytes you asked it to send. If the socket is non-blocking, this means waiting until select() tells you that the socket is writeable before trying again.
First of all, TCP is a byte stream protocol, not a packet-based protocol. Just because you sent a 1024 byte chunk doesn't mean it will be received that way. If you're filling the pipe fast enough to get a zero window condition (i.e., that there is no more room in either a receive buffer or send buffer) then it's very likely that the receiver code will at some point be able to read far more at one time than the size of your "packet".
If you haven't specifically requested non-blocking sockets, then both send and recv will block with a zero window/window full condition rather than return an error.
If you want to paste in the receiver-side code we can take a look, but from what you've described it sounds very likely that your 9344th read is actually getting more bytes than your packet size. Do you check the value returned from recv?
Does in your network iperf also fails to send this number of packets of this size? If not check how they send this amount of data.
Hm, from what I read on Wikipedia this may be some kind of buffer overflow (receiver reports zero receive window). Just a guess though.