我写了一个小服务器
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
int main()
{
int server_fd, newsock_fd, server_len, newsock_len;
struct sockaddr_in server_struct, newsock_struct;
server_fd=socket(AF_INET,SOCK_STREAM,0);
server_struct.sin_family=AF_INET;
server_struct.sin_addr.s_addr=inet_addr("127.0.0.1");
server_struct.sin_port=htons(9734);
server_len=sizeof(server_struct);
newsock_len=server_len;
bind(server_fd,(struct sockaddr *)&server_struct,server_len);
listen(server_fd,5);
while(1)
{
printf("server waiting\n");
newsock_fd=accept(server_fd,(struct sockaddr *)&newsock_fd,&newsock_len);
char ch;
read(newsock_fd,&ch,1);
printf("got charachter %c\n",ch);
close(newsock_fd);
}
return 0;
}
当我运行它时,accept最初会调用块,但是在创建新套接字之后,它不会第二次阻塞。 我得到这种类型的输出: -
server waiting <= blocks initially , started client
got charachter a <= correctly displays the charachetr
server waiting <= expected to be blocked again ????
got charachter a
server waiting
got charachter a
server waiting
我错过了什么吗?
答案 0 :(得分:3)
这一行:
newsock_fd=accept(server_fd,(struct sockaddr *)&newsock_fd,&newsock_len);
我们应该说,相当有趣。
为什么要将newsock_fd
的地址作为第二个参数?那只是在惹麻烦: - )
我认为应该是:
newsock_fd = accept (server_fd, (struct sockaddr *)&newsock_struct, &newsock_len);
答案 1 :(得分:1)
int server_fd, newsock_fd, server_len, newsock_len; struct sockaddr_in server_struct, newsock_struct; /* ... */ newsock_fd=accept(server_fd,(struct sockaddr *)&newsock_fd,&newsock_len);
来自accept(2)
:
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
您正在传递指向文件描述符的指针,而不是struct sockaddr。