c - C语言网络编程中的读取函数

标签 c sockets network-programming connection

我使用这段代码从套接字中读取:

int n ;
char buffer[256];
n = read(newsockfd, buffer, 255);
    if (n < 0)
    {
        error("ERROR reading from socket");
    }

如果必须读取的数据大于 255 字节(例如 1000),则必须进行哪些更改?

我知道更改 char buffer[1000],我需要不同的解决方案。

最佳答案

只需从套接字读取几次,直到获得所有要接收的数据。

例如要接收 1000 个字节,它可能看起来像这样(成功时 read 返回读取的字节数):

int received = 0;
while (received < 1000) {
  n = read(newsockfd, buffer, 255);
  // error checking...
  // do something with the partial data in "buffer"...
  received += n;
}

关于c - C语言网络编程中的读取函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1778741/

相关文章:

python - 加速套接字发送行为(在 Python 中)

c++ - 如何在 Linux 上执行适用于 x86、arm、GCC 和 icc 的原子操作?

c - 菜单功能错误: comparison between pointer and integer [enabled by default]

c++ - 在排序数组中找到a [i] = i的最有效方法是什么?

与Linux中的特定接口(interface)连接

architecture - 服务器一次可以处理多少个客户端?

c - 在 GNU C 中列出时跳过目录

Java:如何在没有异常的情况下停止服务器(关闭套接字)?

iphone - 转换一个NSString

c - 套接字错误 10047