0
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <sys/types.h>
    #include <sys/socket.h>

    int main()
    {
    int server_sockfd,client_sockfd;
    int server_len,client_len;
    struct sockaddr_in server_address;
    struct sockaddr_in client_address;

创建一个新的套接字

    unlink("server_socket");
    server_sockfd=socket(AF_INET,SOCK_STREAM,0);

给它命名

    server_address.sin_family=AF_INET;
    server_address.sin_addr.s_addr=htonl(INADDR_ANY);
    server_address.sin_port=htons(9734);
    server_len=sizeof(server_address);
    bind(server_sockfd,(struct sockaddr *)&server_address,server_len);

设置块

    int flags=fcntl(server_sockfd,F_GETFL,0);
    if(flags&O_NONBLOCK==1){
       printf("NONBLOCK");
    }else{
       printf("BLOCK");
    }
    flags=flags&~O_NONBLOCK;
    fcntl(server_sockfd,F_SETFL,flags);
    if(flags&O_NONBLOCK==1){
       printf("NONBLOCK");
    }else{
       printf("BLOCK");
    }

    listen(server_sockfd,5);
    while(1){
       char ch;
       printf("server waiting\n");
       client_len=sizeof(client_address);
       client_sockfd=
          accept(server_sockfd,(struct sockaddr*)&client_sockfd,&client_len);

它第一次被阻止

      read(client_sockfd,&ch,1);
      ch++;
      write(client_sockfd,&ch,1);
      close(client_sockfd);
   }
}

当客户端首先连接时,我工作,但下一个将无法工作

4

1 回答 1

1

client_address和之间可能发生不匹配client_sockfd

accept()的手册页说:

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

The addrlen argument is a value-result argument: the caller must initialize it to
contain the size (in bytes) of the structure pointed to by addr; on return it
will contain the actual size of the peer address.

尝试:

client_sockfd=
   accept( server_sockfd, (struct sockaddr*)&client_address, &client_len );
于 2013-03-16T22:16:34.933 回答