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