从套接字读取缓冲区

编程入门 行业动态 更新时间:2024-10-27 08:24:37
本文介绍了从套接字读取缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在用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.

更多推荐

从套接字读取缓冲区

本文发布于:2023-07-27 02:45:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓冲区

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!