我正在用c语言编写简单的服务器/客户端,其中服务器临时存储来自客户端的消息,并在客户端请求时检索它。
I'm writing simple server/client in c, where server temporary stores message from client and retrieve it when client request it.
问题是当客户端收到消息时来自服务器的消息,缓冲区有点奇怪。 我所做的全部与从服务器接收到的一样多,并在屏幕上打印出来,但不知何故,缓冲区被覆盖的内容超过了缓冲区的最大大小
The problem is when client receives message from server, the buffer acts kinda weird. All i did is read as much as receive from server and print it on the screen, but somehow buffer was overwrited more than maximum size of buffer
while((byteRead = recv(ssock, buffer, MAXBUF, 0)) > 0) { if(byteRead <= 0) break; printf("%s", buffer); }
其中MAXBUF为256。它包含一些垃圾,因此我检查了字符串大小在缓冲区中,并且令人惊讶地
where MAXBUF is 256. It keep contains some garbages so i examined the string size in buffer and surprisingly
printf("%d READ vs %d buffer strlen \n", byteRead, strlen(buffer))告诉我byteRead为256,但是缓冲区的字符串长度为262。
show me that byteRead is 256 but string length of buffer is 262.
任何想法?
服务器端的Ps,它正确读取文件并将其发送到套接字。
P.s on server side, it reads file correctly and send it onto socket.
推荐答案recv 不会在字符串末尾放置空终止符( printf %s 假设有一个)。
recv does not place a null terminator at the end of the string (whilst printf %s assumes there is one).
您必须使用 byteRead 确定字符串的长度。如果要使用 printf 之类的函数,请添加一个空终止符,但即使在最大大小的读取时,也要确保缓冲区有足够的空间。
You must use byteRead to determine the length of the string. Add a null terminator if you want to use a function like printf, but ensure your buffer has the space for it even on a maximum-size read.
更多推荐
从套接字读取缓冲区
发布评论