我正在用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
....
但是我不确定这是否正确。
答案 0 :(得分:1)
您可以使用以下方法从套接字读取字节。
// 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;
}
答案 1 :(得分:-1)
已经找到了答案,一旦您想再次从套接字读取,套接字上的偏移将更改为您上次使用“ read()”时读取的最后数据,因此我发布的示例是正确的