How can I better read my socket?
This just gets stuck every time I loop it. It sits waiting to read but never reads anything, because, well.. there's nothing left to read.
Here's the read functi开发者_JS百科on:
int readSocket(int sockfd, char* buffer) {
FILE* file;
file = fopen("logfile.txt","a+");
char code[5];
while(1) {
int nBytes = read(sockfd, buffer, MY_BUFFER_SIZE);
fprintf(file,"S->C: %s",buffer);
strncpy(code, buffer,4);
code[4]='\0';
if (nBytes == 0) break;
memset(buffer, 0, MY_BUFFER_SIZE);
}
fclose(file);
return codeParser(atoi(code));
}
Here's what's calling it:
while (1) {
serverCode = readSocket(sockfd, mybuffer);
if (serverCode == 221) break;
fflush (stdout);
buffer = fgets (mybuffer, 1024, stdin);
writeSocket(sockfd, mybuffer);
}
Any suggestions?
TCP socket is a bi-directional stream. It does not know about your message boundaries. You need your own protocol on top of TCP to figure out separate messages. Two Three common approaches are:
- fixed-length messages,
- length of the message embedded into fixed-length message header,
- explicit message delimiter, say a new-line, or
\0x1
, etc. (thanks, @caf).
Edit 0:
Some notes about your code:
- Always check return values of system calls like
read(2)
. First, it might be-1
, i.e. an error, so you have to examineerrno(3)
; second, you might read less then 4 bytes you are expecting. nBytes == 0
is theEOF
case, meaning other side closed the connection.- You don't need the
memset()
there.
精彩评论