繁体   English   中英

C中的非阻塞插座

[英]Non blocking socket in c

目前,我正在使用单个服务器上的单个客户端udp聊天应用程序。 最初我使用阻塞套接字,这是默认条件。 现在,我想将套接字转换为非阻塞状态,以便客户端和服务器之间的通信可以顺利进行……我现在已经在服务器端实现了select函数,但是当它启动客户端时开始发送一次消息,该消息显示在服务器端,此后客户端和服务器均无响应,因此现在我展示如何在服务器端实现select()函数:

            //Declaring a non-blocking structure
              fd_set readfds,writefds;
           // clear the set ahead of time
              FD_ZERO(&readfds);
              FD_ZERO(&writefds);
           // add our descriptor to the set
              FD_SET(sd, &readfds);
              FD_SET(sd, &writefds);
              /value of sd+1
              int n=sd+1;

由于我想同时接收和发送数据,因此我在循环中实现了select函数:

                int client_length = (int)sizeof(struct sockaddr_in);
                int rv = select(n, &readfds, NULL, NULL, NULL);
                if(rv==-1)
                {
                 printf("Error in Select!!!\n");
                 exit(0);
                }
               else if(rv==0)
                { 
                 printf("Timeout occurred\n");
                }
               else 
                if (FD_ISSET(sd, &readfds))
                {
                int bytes_received = recvfrom(sd, buffer,SIZE, 0, (struct sockaddr *)&client, &client_length);
                if (bytes_received < 0)
               {
               fprintf(stderr, "Could not receive datagram.\n");
               closesocket(sd);
               WSACleanup();
               exit(0);
              }
                }

进一步发送数据:

              fgets(buffer,SIZE,stdin);
              int rv1 = select(n, &writefds, NULL, NULL, NULL);
              if(rv1==-1)
              {
           printf("Error in Select!!!\n");
           exit(0);
              }
             else if(rv1==0)
             {
            printf("Timeout occurred\n");
             }
            else 
             if(FD_ISSET(sd,&writefds))
                  {
                     if(sendto(sd, buffer,strlen(buffer), 0, (struct sockaddr *) &client,client_length)<0)
                         {
                            printf("Error sending the file! \n");
                            exit(1);
                         }
                  }

                }

因此,如果somoone让我知道我是否正确执行此操作,我将不胜感激,如果可以,那么客户端上的相同实现可以解决我的问题吗?

这是不正确的:

select(n, &writefds, NULL, NULL, NULL);

第二个参数仅用于检查可读性。 要检查可写性,请使用第三个参数:

select(n, NULL, &writefds, NULL, NULL);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM