Вопрос

I am new to c++. I understand Object Oriented Programming.

I followed a tutorial and put together this Client/Server code. I would now like to add a message to the server when a client is disconnected.

im using vs11

Server:

#include "main.h"

using namespace std;

void main ( )
{
    long answer;
    WSAData wsaData;
    WORD DLLVERSION;
    DLLVERSION = MAKEWORD(2,1);

    answer = WSAStartup(DLLVERSION, &wsaData);

    //WINSOCK LOADED

    SOCKADDR_IN addr;
    int addrlen = sizeof(addr);

    SOCKET sListen;
    SOCKET sConnect;
    SOCKET* Connections;
    static int ConCounter = 0;

    Connections = (SOCKET*)calloc(64, sizeof(SOCKET));

    sConnect = socket(AF_INET,SOCK_STREAM,NULL);

    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    addr.sin_family = AF_INET;

    addr.sin_port = htons(1234);


    sListen = socket(AF_INET,SOCK_STREAM,NULL);

    bind(sListen, (SOCKADDR*)&addr, sizeof(addr));

    listen(sListen, SOMAXCONN);

    for(;;)
    {
        cout << "Wating for connection..." <<endl;

        if(sConnect = accept(sListen, (SOCKADDR*)&addr, &addrlen))
        {
            Connections[ConCounter] = sConnect;

            cout << "Connection found " << ConCounter <<endl;

            answer = send(Connections[ConCounter], "YourMessage", 12, NULL);

            ConCounter++;
        }
    }
}    

Client:

#include "main.h"

using namespace std;

void main ( )
{
    string confirm;
    char message[200];
    string strmessage;

    long answer;
    WSAData wsaData;
    WORD DLLVersion;
    DLLVersion = MAKEWORD(2,1);
    answer = WSAStartup(DLLVersion, &wsaData);

    SOCKADDR_IN addr;

    int addrlen = sizeof(addr);

    SOCKET sConnect;

    sConnect = socket(AF_INET, SOCK_STREAM,NULL);



    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    addr.sin_family = AF_INET;


    addr.sin_port = htons(1234);

    cout << "Do you want to connect to the Server? [Y/N]" <<endl;
    cin >> confirm;

    if(confirm == "N")
    {
        exit(1);
    }
    else
    {
        if(confirm == "Y")
        {
            connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));

            answer = recv(sConnect, message, sizeof(message), NULL);

            strmessage = message;
            cout << strmessage <<endl;

            getchar();
        }
    }
    getchar();
}
Это было полезно?

Решение

You can't detect it with your present code, because all your present server does is send one message to a newly accepted connection, which isn't likely to fail, and then completely forget about that connection., including leaking its socket into hyperspace.

You need to either start a new thread per connection, that will deal with all I/O on that connection including disconnects (signaled by recv() returning zero) or errors (signaled by -1 returns from send() or recv())., or else go to Async or multiplexed I/O, which is two whole nuther kettles of fish.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top