c ++服务器中的多个客户端

时间:2014-11-24 19:40:00

标签: c++ client-server

昨天我开始为服务器客户端TCP / IP编写一个用于聊天的代码。

服务器的代码:

#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSAData wsa;
    WORD Version = MAKEWORD(2, 1);

    WSAStartup(Version, &wsa);

    SOCKET Listen = socket(AF_INET, SOCK_STREAM, 0);
    SOCKET Connect = socket(AF_INET, SOCK_STREAM, 0);

    SOCKADDR_IN Server;

    Server.sin_addr.s_addr = inet_addr("127.0.0.1");
    Server.sin_family = AF_INET;
    Server.sin_port = htons(100);

    bind(Listen, (SOCKADDR*)&Server, sizeof(Server));
    listen(Listen, 1);
    int size = sizeof(Server);
    char buffer[512];
    char *fn = "";
    int iResult;
    std::cout <<"Listening...";

    if(Connect = accept(Listen, (SOCKADDR*)&Server, &size)) {
        std::cout << "\nConnecting was reached :)";
    }


do {

       char *fn;

iResult = recv(Connect, buffer, sizeof(buffer), 0);
if (iResult > 0) {
buffer[iResult] = '\0';
fn = buffer;
        std::cout << fn;
} else if (iResult == 0){
            printf("Connection closing...\n");
        iResult = 0;
}


    } while (iResult > 0);


    WSACleanup();
    std::cin.get();
    return 0;
}

对于客户来说:

#include <iostream>
#include <winsock2.h>
#include <string>

#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSAData wsa;
    WORD Version = MAKEWORD(2, 1);

    WSAStartup(Version, &wsa);

    int iResult;

    std::string text;
char buffer[512];

    SOCKADDR_IN Client;

    Client.sin_addr.s_addr = inet_addr("127.0.0.1");
    Client.sin_family = AF_INET;
    Client.sin_port = htons(100);

    SOCKET Connect = socket(AF_INET, SOCK_STREAM, 0);

    std::cout << "Wcisnij enter aby polaczyc";
    std::cin.get();



    if(connect(Connect, (SOCKADDR*)&Client, sizeof(Client))) {
        std::cout << "Nawiazano polaczeniee";
    }

    do {

    std::cout << "Waxer: ";
        std::cin >> text;
        text.insert( 0, "Waxer: " );
strcpy_s(buffer, text.c_str());

// Send an initial buffer
    iResult = send(Connect, buffer, strlen(buffer), 0);
    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(Connect);
        WSACleanup();
        return 1;
    }


    } while(text != "ban");

    std::cout<< "Polaczenie wyslane!";
    std::cin.get();
    return 0;
}

我的问题是?我应该在此代码中为多个客户端更改什么。我的意思是如何连接新客户?

1 个答案:

答案 0 :(得分:0)

你的问题非常开放,但一般来说你需要线程。

伪代码:

int main() 
{
  std::vector<std::thread> clients;
  Socket listener("localhost", "1337");

  for (;;)
  {
    Socket tmp = listener.accept();
    clients.push_back(std::thread(&myHandlerFunction, tmp));
    clients.back().detach();      
  }
}

最后,每个连接的客户端都有一个线程,可以编写聊天逻辑,以便他们可以相互通信。