我想写一个实验性的客户端/服务器程序来证明写入失败或发送缓冲区已满时阻止。 基本上,我在发件人程序上有一个无限循环,我使用select()来检查是否可以在缓冲区上写入(我认为这意味着套接字缓冲区未满),如果我可以在缓冲区上写入比我写()一个字符。当FD_ISSET(sockfd,& writefds)为假(我无法在缓冲区写入,因为它已满)时,循环中断。 开始阅读前,接收器程序正在睡眠一分钟()。我希望发件人在这个睡眠时间内填充缓冲区,但事实上,程序永远不会结束。C - 填充TCP套接字发送缓冲区
发件人:
int main(int argc, char *argv[]) {
char buffer[100];
int sockfd, total = 0, bytes = 0;
fd_set writefds;
sockfd = dial(argv[1], argv[2]);
bzero(buffer, sizeof buffer);
while(1)
{
int ret = 0;
FD_ZERO(&writefds);
FD_SET(sockfd, &writefds);
if((ret = select(sockfd + 1, NULL, &writefds, NULL, 0)) < 0)
{
perror("select");
exit(errno);
}
if(FD_ISSET(sockfd, &writefds))
{
write(sockfd, "a", 1);
total++;
continue;
}
else
{
puts("I can't write in the socket buffer");
break;
}
}
printf("nb chars written: %d\n", total);
return 0;
}
reciever:
int foo(int sockfd) {
char buffer[100];
int t, total = 0;
bzero(buffer, sizeof buffer);
printf("I have a new client\n");
sleep(60);
while((t = read(sockfd, buffer, sizeof buffer)) > 0)
{
total += t;
printf("%d ", total);
}
printf("nb chars read: %d\n", total);
if(t < 0)
{
perror("read");
}
printf("I don't have that client anymore\n");
return 0;
}
你应该添加你的代码来创建套接字,以确保它是面向连接的而不是UDP。 – trev