检测断开连接Winsock C ++

时间:2013-10-09 05:41:21

标签: c++ visual-studio-2012 winsock winsock2

我是c ++的新手。我理解面向对象编程。

我按照教程编写了这个客户端/服务器代码。我现在想在客户端断开连接时向服务器添加消息。

即时通讯使用vs11

服务器:

#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++;
        }
    }
}    

客户:

#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();
}

1 个答案:

答案 0 :(得分:3)

您无法使用当前代码检测到它,因为您当前所有服务器都会向新接受的连接发送一条消息,这可能不会失败,然后完全忘记该连接。插入超空间。

你需要为每个连接启动一个新线程,它将处理该连接上的所有I / O,包括断开连接(由recv()返回零信号发出的信号)或错误(由send()或recv返回-1表示())。或者转到异步或多路复用I / O,这是两个完整的鱼类水壶。