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 function:
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:
\\0x1
, etc. (thanks, @caf). Some notes about your code:
read(2)
. First, it might be -1
, ie an error, so you have to examine errno(3)
; second, you might read less then 4 bytes you are expecting. nBytes == 0
is the EOF
case, meaning other side closed the connection. memset()
there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.