如何解决这个socket连接?

时间:2014-01-22 15:45:07

标签: c sockets tcp ip port

以下代码是一个服务器代码,它接受来自客户端的连接,服务器将仅在第一次向客户端发送响应。但是我的客户端只有在三次向服务器发送请求并返回响应后才会连接。但我的代码只是第一次向主服务器发送响应,之后重置。

   SOCKET sock;
        SOCKET fd;
    uint16 port = 18001;
    void CreateSocket()
    {
       struct sockaddr_in server, client;  // creating a socket address structure: structure contains ip address and port number
      WORD wVersionRequested;
    WSADATA wsaData;
    int len;

        printf("Initializing Winsock\n");


        wVersionRequested = MAKEWORD (1, 1);
        if (WSAStartup (wVersionRequested, &wsaData) != 0){
            printf("Winsock initialised failed \n");
        } else {
            printf("Initialised\n");
        }


        // create socket
        sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (sock < 0)    {
            printf("Could not Create Socket\n");
            //return 0;
        }

        printf("Socket Created\n");

        // create socket address of the server
        memset( &server, 0, sizeof(server));
        // IPv4 - connection
        server.sin_family = AF_INET;
        // accept connections from any ip adress
        server.sin_addr.s_addr = htonl(INADDR_ANY);
        // set port
        server.sin_port = htons(18001);


        //Binding between the socket and ip address
        if(bind (sock, (struct sockaddr *) &server, sizeof(server)) < 0)
        {
            printf("Bind failed with error code: %d", WSAGetLastError());
        }

        //Listen to incoming connections
        if(listen(sock,3) == -1){
            printf("Listen failed with error code: %d", WSAGetLastError());
        }

        printf("Server has been successfully set up - Waiting for incoming connections");

        for(;;){
            len = sizeof(client);
            fd = accept(sock, (struct sockaddr*) &client, &len);

            if (fd < 0){
                printf("Accept failed");
                //closesocket(sock);
            }

            printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
    closesocket(fd);
    }

}

任何人都可以帮我解决问题:上面的代码应该接受连接,并至少三次向客户端发送响应。

0 个答案:

没有答案