socket编程c ++窗口,看不到来自服务器

时间:2016-05-02 10:28:45

标签: c++ windows sockets visual-studio-2015

我正在编写网络客户端 - 服务器程序:

服务器端:

#include "stdafx.h"
#include <winsock.h>
#include <stdio.h>
#include<stdlib.h>

#define PROTOPORT 5193
#define QLEN 6
#define BUFFERSIZE 512

void ErrorHandler(char *errorMessage)
{
    printf(errorMessage);
}


void ClearWinSock()
{
#if defined WIN32
    WSACleanup();
#endif
}


int main(int argc, char *argv[])
{
    int port;

    if (argc > 1)
        port = atoi(argv[1]);
    else
        port = PROTOPORT;

    if (port < 0) {
        printf("Bad port number %s \n", argv[1]);
        return 0;
    }

#if defined WIN32
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

    if (iResult != 0) {
        ErrorHandler("Error at WSAStartup()\n");
        return 0;
    }
#endif

    //creazione della socket
    int MySocket;
    MySocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (MySocket < 0) {
        ErrorHandler("socket creation failed.\n");
        ClearWinSock();
        return 0;
    }

    //ASSEGNAZIONE DI UN INDIRIZZO ALLA SOCKET
    struct sockaddr_in sad;
    memset(&sad, 0, sizeof(sad)); // ensures that extra bytes contain 0
    sad.sin_family = AF_INET;
    sad.sin_addr.s_addr = inet_addr("127.0.0.1");
    sad.sin_port = htons(port); /* converts values between the host and
                                network byte order. Specifically, htons() converts 16-bit quantities
                                from host byte order to network byte order. */
    if (bind(MySocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
        ErrorHandler("bind() failed.\n");
        closesocket(MySocket);
        ClearWinSock();
        return 0;
    }

    // SETTAGGIO DELLA SOCKET ALL'ASCOLTO
    if (listen(MySocket, QLEN) < 0) {
        ErrorHandler("listen() failed.\n");
        closesocket(MySocket);
        ClearWinSock();
        return 0;
    }

    // ACCETTARE UNA NUOVA CONNESSIONE
    struct sockaddr_in cad; // structure for the client address
    int clientSocket; // socket descriptor for the client
    int clientLen; // the size of the client address

    printf("Waiting for a client to connect...");

    while (1) {
        clientLen = sizeof(cad); // set the size of the client address
        if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
            &clientLen)) < 0) {
            ErrorHandler("accept() failed.\n");

            //RICEZIONE DATI TEST
            int bytesRcvd;
            int totalBytesRcvd = 0;
            int Csocket;
            Csocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

            char buf[BUFFERSIZE]; // buffer for data from the server
            printf("Received: "); // Setup to print the echoed string


                if ((bytesRcvd = recv(Csocket, buf, BUFFERSIZE - 1, 0)) <= 0) {
                    ErrorHandler("recv() failed or connection closed prematurely");
                    closesocket(Csocket);
                    ClearWinSock();
                    return 0;
                                                            }

                totalBytesRcvd += bytesRcvd; // Keep tally of total bytes
                buf[bytesRcvd] = '\0'; // Add \0 so printf knows where to stop
                printf("%s", buf); // Print the echo buffer


            // CHIUSURA DELLA CONNESSIONE
            closesocket(MySocket);
            ClearWinSock();
            return 0;
        }
        printf("Handling client %s\n", inet_ntoa(cad.sin_addr));
    }




}

和客户方:

#include "stdafx.h"
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFERSIZE 512
#define PROTOPORT 5193

void ErrorHandler(char *errorMessage) {
    printf(errorMessage);
}

void ClearWinSock() {
    WSACleanup();
}


int main(void) {

    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

    if (iResult != 0) {
        printf("error at WSASturtup\n");
        return 0;
                      }

    // CREAZIONE DELLA SOCKET
    int Csocket;
    Csocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (Csocket < 0) {
        ErrorHandler("socket creation failed.\n");
        closesocket(Csocket);
        ClearWinSock();
        return 0;
                    }

    // COSTRUZIONE DELL’INDIRIZZO DEL SERVER
    struct sockaddr_in sad;
    memset(&sad, 0, sizeof(sad));
    sad.sin_family = AF_INET;
    sad.sin_addr.s_addr = inet_addr("127.0.0.1"); // IP del server
    sad.sin_port = htons(5193); // Server port

    // CONNESSIONE AL SERVER
    if (connect(Csocket, (struct sockaddr *)&sad, sizeof(sad)) < 0)
    {
        ErrorHandler("Failed to connect.\n");
        closesocket(Csocket);
        ClearWinSock();
        return 0;
    }

    char* inputString = "prova"; // Stringa da inviare
    int stringLen = strlen(inputString); // Determina la lunghezza


    // INVIARE DATI AL SERVER
    if (send(Csocket, inputString, stringLen, 0) != stringLen) {
        ErrorHandler("send() sent a different number of bytes than expected");

        closesocket(Csocket);
        ClearWinSock();
        return 0;
    }


    // RICEVERE DATI DAL SERVER
    int bytesRcvd;
    int totalBytesRcvd = 0;
    char buf[BUFFERSIZE]; // buffer for data from the server
    printf("Received: "); // Setup to print the echoed string

    while (totalBytesRcvd < stringLen) {
        if ((bytesRcvd = recv(Csocket, buf, BUFFERSIZE - 1, 0)) <= 0) {
            ErrorHandler("recv() failed or connection closed prematurely");
            closesocket(Csocket);
            ClearWinSock();
            return 0;
                                                                        }
        totalBytesRcvd += bytesRcvd; // Keep tally of total bytes
        buf[bytesRcvd] = '\0'; // Add \0 so printf knows where to stop
        printf("%s", buf); // Print the echo buffer
                                        }

    // CHIUSURA DELLA CONNESSIONE
    closesocket(Csocket);
    ClearWinSock();
    printf("\n"); // Print a final linefeed
    system("pause");
    return(0);
}

我输出的字符串i从客户端传递到服务器时遇到问题:&#34; prova&#34;。

有人能告诉我错误在哪里吗?代码没有给我任何错误。

3 个答案:

答案 0 :(得分:3)

仅在accept失败时才会收到数据:

if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
        &clientLen)) < 0) {
        ErrorHandler("accept() failed.\n");

        int bytesRcvd;
        int totalBytesRcvd = 0;
        ...

您需要做的只是添加else案例:

if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
        &clientLen)) < 0) {
        ErrorHandler("accept() failed.\n");
} else {

        int bytesRcvd;
        int totalBytesRcvd = 0;
        ... // receive code here

        // clientSocket is the socket to communicate with client
        // call recv on it, not the other socket you created in the loop

}

答案 1 :(得分:3)

accept()调用返回&#39; clientSocket&#39;,你会立即忽略并梦想一些新的&#39; Csocket&#39;接收。

不要这样做。

if ((bytesRcvd = recv(clientSocket, buf, BUFFERSIZE - 1, 0)) <= 0) {

答案 2 :(得分:0)

这是新的服务器端:

#include "stdafx.h"
#include <winsock.h>
#include <stdio.h>
#include<stdlib.h>

#define PROTOPORT 5193
#define QLEN 6
#define BUFFERSIZE 512

void ErrorHandler(char *errorMessage)
{
    printf(errorMessage);
}


void ClearWinSock()
{
#if defined WIN32
    WSACleanup();
#endif
}


int main(int argc, char *argv[])
{
    int port;

    if (argc > 1)
        port = atoi(argv[1]);
    else
        port = PROTOPORT;

    if (port < 0) {
        printf("Bad port number %s \n", argv[1]);
        return 0;
    }

#if defined WIN32
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

    if (iResult != 0) {
        ErrorHandler("Error at WSAStartup()\n");
        return 0;
    }
#endif

    //creazione della socket
    int MySocket;
    MySocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (MySocket < 0) {
        ErrorHandler("socket creation failed.\n");
        ClearWinSock();
        return 0;
    }

    //ASSEGNAZIONE DI UN INDIRIZZO ALLA SOCKET
    struct sockaddr_in sad;
    memset(&sad, 0, sizeof(sad)); // ensures that extra bytes contain 0
    sad.sin_family = AF_INET;
    sad.sin_addr.s_addr = inet_addr("127.0.0.1");
    sad.sin_port = htons(port); /* converts values between the host and
                                network byte order. Specifically, htons() converts 16-bit quantities
                                from host byte order to network byte order. */
    if (bind(MySocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
        ErrorHandler("bind() failed.\n");
        closesocket(MySocket);
        ClearWinSock();
        return 0;
    }

    // SETTAGGIO DELLA SOCKET ALL'ASCOLTO
    if (listen(MySocket, QLEN) < 0) {
        ErrorHandler("listen() failed.\n");
        closesocket(MySocket);
        ClearWinSock();
        return 0;
    }

    // ACCETTARE UNA NUOVA CONNESSIONE
    struct sockaddr_in cad; // structure for the client address
    int clientSocket; // socket descriptor for the client
    int clientLen; // the size of the client address

    printf("Waiting for a client to connect...");

    while (1) {
        clientLen = sizeof(cad); // set the size of the client address
        if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,
            &clientLen)) < 0) {
            ErrorHandler("accept() failed.\n");
        }else{

            //RICEZIONE DATI TEST
            int bytesRcvd;
            int totalBytesRcvd = 0;

            char buf[BUFFERSIZE]; // buffer for data from the server
            printf("Received: "); // Setup to print the echoed string


                if ((bytesRcvd = recv(clientSocket, buf, BUFFERSIZE - 1, 0)) <= 0) {
                    ErrorHandler("recv() failed or connection closed prematurely");
                    closesocket(clientSocket);
                    ClearWinSock();
                    return 0;

                totalBytesRcvd += bytesRcvd; // Keep tally of total bytes
                buf[bytesRcvd] = '\0'; // Add \0 so printf knows where to stop
                printf("%s", buf); // Print the echo buffer
                } Sleep(10);


            // CHIUSURA DELLA CONNESSIONE
            closesocket(MySocket);
            ClearWinSock();
            return 0;
        }
        printf("Handling client %s\n", inet_ntoa(cad.sin_addr));
        system("pause");
    }

}