如何检查套接字上是否有数据?

时间:2014-01-12 12:08:43

标签: c windows api sockets

SOCKET s;   // Create a SOCKET for listening for
            // incoming connection requests.
SOCKET new_socket;  // create a socket for accepting incoming connection
uint16 port =18001;


void CreateSocket()
{
    int sin_size;   
    WSADATA wsa;
        struct sockaddr_in server, master;  // creating a socket address structure: structure contains ip address and port number


            printf("Initializing Winsock\n");
        if(WSAStartup(MAKEWORD(2,2), &wsa)!=0)
        {
            printf("Failed Error Code: %d", WSAGetLastError());
            return -1;
        }
        printf("Initialised\n");


        //CREATING a SOCKET

        if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        {
            printf("Could not Create Socket\n");
            //return 0;
        }
        printf("Socket Created\n");

        server.sin_addr.s_addr = inet_addr("192.168.0.1");
        server.sin_family = AF_INET;     
        server.sin_port = htons(port); 


        //Binding between the socket and ip address

        if(bind (s, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR)
        {
            printf("Bind failed with error code: %d", WSAGetLastError());
        }
        puts("Bind Done");


        //Listen to incoming connections
        listen(s, 3);


        //Accepting the incoming connection


                    sin_size = sizeof(struct sockaddr_in);

            new_socket = accept(s, (struct sockaddr *)&master, &sin_size);

            printf("\n I got a connection from (%s , %d)",
                   inet_ntoa(master.sin_addr),ntohs(master.sin_port));
            closesocket(new_socket);


            /*new_socket = accept(s, NULL, NULL);

           if (new_socket == INVALID_SOCKET)
           {
        printf("accept failed with error: %ld\n", WSAGetLastError());
        closesocket(new_socket);
        WSACleanup();
        return 1;
    } 
           else
        printf("Client connected.\n");*/
}

我已创建套接字并接受来自主服务器的连接但是有人告诉我检查指定端口号上是否有可用数据的条件?我正在使用Windows操作系统。上面的代码用于为Windows操作系统创建套接字。

如何使上面的代码接受端口号作为发送和接收数据的参数??

1 个答案:

答案 0 :(得分:3)

您可以在线轻松找到它。

假设您正在使用winsock API,您只需要调用recvfrom() - 它会在出现问题时返回错误,或者在有可用的传入数据之前阻止它。

请参阅此处的文档:http://msdn.microsoft.com/en-us/library/windows/desktop/ms740120%28v=vs.85%29.aspx