0

我是 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();
}
4

1 回答 1

3

您无法使用当前代码检测到它,因为您当前的服务器所做的只是向新接受的连接发送一条消息,该连接不太可能失败,然后完全忘记该连接。包括将其套接字泄漏到超空间中.

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

于 2013-10-09T09:27:11.547 回答