坚持接受插座

时间:2016-01-20 21:48:10

标签: sockets winsock

我刚刚将一些套接字代码从Linux移到了Windows。经过一些更改以使代码在Windows上运行后,我的客户端似乎在等待accept函数并且没有从服务器接收我的数据。

我客户端版本的代码

   WSADATA wsa;
   SOCKET sock = 0;
   struct sockaddr_in server;
   packageLength = 64;//We don't need more to get all the information
   char * buffer = new char[packageLength];

   if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { this->Die("Failed to WSA startup");}

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        this->Die("Failed to create socket");
   }

    memset(&server, 0, sizeof(server));
   server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
   server.sin_port = htons(55555);

    if (bind(sock, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR) { 
       this->Die("Failed to bind the server socket"); 
   }
    if (listen(sock, 1) < 0) {  
       this->Die("Failed to listen on server socket");
   }

    SOCKET clientSocket = 0;
   struct sockaddr_in client;
   int size = sizeof(sockaddr_in);

   std::cout << "Waiting for server" << std::endl;
   clientSocket = accept(sock, (struct sockaddr *) &client, &size); //Stands here and wait  
   if (clientSocket == INVALID_SOCKET) {
        this->Die("Failed to accept client");
   }
   //Never reach here
    std::cout << "Server accepted" << std::endl;

服务器端的代码

    WSADATA wsa;
    SOCKET sock = 0;
    struct sockaddr_in sender;
    char* buffer = new char[this->packageLength];

    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
        this->Die("Failed to WSA startup");
    }

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket : %d", WSAGetLastError());
        this->Die("Failed to create socket");
    }

    memset(&sender, 0, sizeof(sender));
    sender.sin_family = AF_INET;
    sender.sin_addr.s_addr = inet_addr(ip.c_str());
    sender.sin_port = htons(this->port);

    //Connect to the recevier
    if (bind(sock, (struct sockaddr *) &sender, sizeof(sender)) == SOCKET_ERROR) {
        this->Die("Failed to connect to recevier");
    }

    //Send all data
    int amountLeft = (int)amount;
    while (amountLeft > 0) {
        //Send on chunk of data. //Packagesize is actually the size of the data portion
        std::cout << "Sent" << std::endl;
        send(sock, data, strlen(data), 0);

        amountLeft -= packageLength;
    }

    std::cout << "All data is sent, socket is now closed" << std::endl;

服务器发送数据但客户端没有收到数据。我检查过端口是正确的,它是本地主机所以使用的IP是127.0.0.1

1 个答案:

答案 0 :(得分:1)

  

我刚将一些套接字代码从Linux移动到Windows。

此代码从未在任何平台上运行。移动非工作代码毫无意义。

  

我的客户......

没有客户。这不是客户端和服务器。它是两台服务器。

  

......似乎在等待accept()功能。

没有客户端等待accept()功能。 accept()用于服务器,而不是客户端。你在这里认真地回到了前面。服务器应致电listen()accept();客户应拨打connect().