Home > OS >  Windows socket TCP communications problems
Windows socket TCP communications problems

Time:11-19


My desktop of two processes using a socket to inter-process communication, using TCP protocol, then the packet is the head body size (data) + 4 bytes body
Read function to read the first four bytes at a time, and then the four bytes can determine the size of the body, then read the body length of bytes, most of the time are working well,


 
//pseudo code
Packet {
BYTE head [4].
Char * body;
Uint length () {return head converting integers; };
}

//read cycle
While (1) {
Packet p;
Int nRead=read (fd, p.h ead,.. 4);
If (nRead==4) {
Uint length=p.l ength ();
P.b ody=malloc (p.l ength ());
Int nRead=read (fd, p.b ody,.. Length);
//handle the body data
//free body
}
}




Sometimes, however, the read will appear after 4 bytes read head, did not read the body length bytes, read as if to return, and then the next, while reading 4 bytes read from inside the body is the last remaining bytes, so will be the wrong length (usually billions,,,), cause the malloc/new collapse,

Now the question is, what kind of situation will cause the read haven't read the specified number of bytes is returned, I remember in Linux cause signal signal read returns? In the Windows? The reason for this may be because the debugging? Still says code would have a problem, no handle all Socket Tcp communications in sudden situation?



CodePudding user response:

TCP communication code, didn't have, to learn

CodePudding user response:

Stick pack, finished in the first four bytes length, open up a specified length of buffer, always read buffer is full, in order to be a package over, to start your business at this moment,
Like this:
(the head) (bo

Dy) (head) (bod

Y)
Should be at the back of the head read the fixed body is loaded,
In addition, followed by four bytes is the new package, need to enter the new business logic,
  • Related