c - 在不知道数据长度的情况下读取套接字中发送的数据 block

标签 c sockets

我正在用 C 创建 WebSocket 代码,并且尝试读取套接字的部分内容并将每个部分存储到缓冲区地址。例如,我在套接字中发送了一个字符串:

ABCD......

如何从套接字读取它并将每个字符放入缓冲区地址

BUF[0],BUF[1],.....

我想使用read(socket,...,...);

我尝试这样做:

read(socket, buf[0],1); // for reading first byte of the socket 
read(socket, buf+1,1); // for reading 2nd byte of the socket
....

但我不确定这是否是正确的方法。

最佳答案

您可以使用以下方法从套接字读取字节。

// It's a good idea to read some bytes at a time
char buffer[1024]; 

// Buffer index
int index = 0;

// Bytes read by the socket in one go
ssize_t bytesRead;


while (1) // break condition specified on the basis of bytes read
{
    bytesRead = read(socket, buffer + index, sizeof(buffer) - index);   

    if ( bytesRead <= 0 )
    {
         // No more bytes to read from the socket, terminate the loop
         break;
    }

    // bytesRead has the number of bytes that have been already read,
    // Use it to increment the buffer index.
    index += bytesRead;
}

关于c - 在不知道数据长度的情况下读取套接字中发送的数据 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847256/

相关文章:

c - 生成文件的问题

C - PlaySound() 在将位置作为 char[] 传递时找不到文件

c - 展开一个非指针数组

c# - 异步/等待高性能服务器应用程序?

sockets - IPC速度及比较

c++ - 委托(delegate)使用 boost asio TCP/IP 套接字

c - 用C有效迁移一个linux进程

c - 矩阵乘法分割错误?

c - 获取地址信息错误 : ai_socktype not supported

c# - .NET 3.0 或更高版本的套接字圣经