c - Socket data length questions -


i have couple of questions related following code:

char buffer[256]; memset(buffer,0,256);  read(socket_fd,buffer,255); 

the questions:

  1. why read 255 not 256 ?
  2. let's want send word: "cool" client server. how many bytes should write "in client" , how many bytes should read "in server"?

i'm confused.

you have answers here, think there's concept should explain.

when send data through streams (that is, writes number of bytes 1 end, , bytes can read in same order in other end), want know when stop reading. mandatory if you'll send more 1 thing: when first message stop, , second begin? in stream, things mixed up.

so, how delimit messages? there 3 simple ways (and many other not simple ones, of course):

1 fixed-length messages: if know beforehand every message is, say, 10-bytes long, don't have problem. read 10 bytes, , 11th 1 part of message. extremely simple, extremely rigid.

2 delimiting characters, or strings: if sending human-readable text, might delimit messages same way delimit strings in char*'s: putting 0 character @ end. way, when read 0, know message ended , remaining data in stream belongs message.

this okay ascii text, when comes arbitrary data it's kinda rigid: there's character, or sequence of characters, messages can't contain (or program confused message ends).

3 message headers: best approach arbitrary length, arbitrary content messages. before sending actual message data, send fixed-length header (or use technique nr 2 mark end of header), specifying metadata message. example, it's length.

say want send message 'cool', said. well, first send byte (or 2-byte short, or 4-byte integer, or whatever) containing '4', length of message, , receive on other end. know before message arrives, must read 1 byte (or 2o, or 4, or whatever), store somewhere , read remaining specified bytes.

very simple example:

struct mheader {     int length; };  (...) struct mheader in_h; read(fd, &in_h, sizeof(struct mheader);  if (in_h.length > 0)     read(fd, buffer, in_h.length) 

hope helps. luck!


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -