我对 C 中的套接字编程有点困惑。
You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article Network programming under Unix systems http://users.actcom.co.il/~choo/lupg/tutorials/internetworking/internet-theory.html to be very informative.
让我困惑的是数据到达套接字的时间。
您如何知道数据包何时到达以及数据包有多大,您是否必须自己完成所有繁重的工作?
我在这里的基本假设是数据包可以是可变长度的,因此一旦二进制数据开始出现在套接字中,您如何开始从中构建数据包?
简而言之,您必须自己完成所有繁重的工作。您可以收到通知,有数据可供读取,但您不知道有多少字节可用。在大多数使用可变长度数据包的 IP 协议中,数据包前面都会有一个已知固定长度的标头。该标头将包含数据包的长度。您读取标头,获取数据包的长度,然后读取数据包。您重复此模式(读取标头,然后读取数据包)直到通信完成。
从套接字读取数据时,您请求一定数量的字节。读取调用可能会阻塞,直到读取请求的字节数,但它返回的字节数可能少于请求的字节数。发生这种情况时,您只需重试读取,请求剩余字节。
下面是一个典型的 C 函数,用于从套接字读取一定数量的字节:
/* buffer points to memory block that is bigger than the number of bytes to be read */
/* socket is open socket that is connected to a sender */
/* bytesToRead is the number of bytes expected from the sender */
/* bytesRead is a pointer to a integer variable that will hold the number of bytes */
/* actually received from the sender. */
/* The function returns either the number of bytes read, */
/* 0 if the socket was closed by the sender, and */
/* -1 if an error occurred while reading from the socket */
int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead)
{
*bytesRead = 0;
while(*bytesRead < bytesToRead)
{
int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead);
if(ret <= 0)
{
/* either connection was closed or an error occurred */
return ret;
}
else
{
*bytesRead += ret;
}
}
return *bytesRead;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)