2014-02-04 2 views
1

Я пытаюсь получить класс связи, который я создал на основе MSDN Winsocket Пример: http://msdn.microsoft.com/en-us/library/windows/desktop/ms737889(v=vs.85).aspx.С ++ Сетевой класс с потоками

При строительстве, я получаю сообщение об ошибке:

"Error 1 error C3867: 'Communication::AcceptClients': function call missing argument list; use '&Communication::AcceptClients' to create a pointer to member c:\users\bobby black\documents\visual studio 2012\projects\communication\communication\communication.cpp 67" 

Чтение через Google, я обнаружил, что статические функции должны быть использованы при создании темы внутри класса; но при реализации этого у меня, похоже, возникают проблемы с назначением connectSocket, listenSocket и * IP для этого экземпляра класса. Я хочу использовать их так, чтобы можно было использовать client.Send(). Я знаю, сервер.Send() в настоящее время не работает. Я просто хотел бы сначала отправить клиента.

Какой практический способ решить эту проблему без использования встроенной сетевой библиотеки?

Source.cpp

#include "Communication.h" 

void main() 
{ 
    Communication server; 
    server.Listen("2000"); 
    Communication client; 
    client.Connect("LOCALHOST", "2000"); 
    client.Send("Hello world!"); 
    Sleep(120000); 
} 

Communication.h

#pragma once 

#undef UNICODE 
#define WIN32_LEAN_AND_MEAN 

#include <iostream>  // std::printf_s 
#include <thread>  // std::thread 
#include <winsock2.h> // WSADATA, SOCKET, ZeroMemory(), WSACleanup(), socket(), listen() 
#include <windows.h> // Sleep 
#include <ws2tcpip.h> // freeaddrinfo(), getaddrinfo() 
#pragma comment (lib, "Ws2_32.lib") //External References 

class Communication 
{ 
public: 
    SOCKET connectSocket; 
    SOCKET listenSocket; 
    char *IP; 
    int Listen(PCSTR port); 
    void WINAPI AcceptClients(); 
    void WINAPI Receive(); 
    int Connect(PCSTR hostname, PCSTR port); 
    int Send(std::string text); 
}; 

Communication.cpp вызов функции

#include "Communication.h" 

int Communication::Listen(PCSTR port) 
{ 
    WSADATA wsaData; 
    int iResult; 
    struct addrinfo *result = NULL, hints; 

    // Initialize Winsock 
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); 
    if (iResult != 0) 
    { 
     printf_s("WSAStartup failed with error: %d\n", iResult); 
     return 0; 
    } 
    printf_s("Initialize Winsock complete\n"); 

    ZeroMemory(&hints, sizeof(hints)); 
    hints.ai_family = AF_INET; 
    hints.ai_socktype = SOCK_STREAM; 
    hints.ai_protocol = IPPROTO_TCP; 
    hints.ai_flags = AI_PASSIVE; 

    // Resolve the server address and port 
    iResult = getaddrinfo(NULL, port, &hints, &result); 
    if (iResult != 0) 
    { 
     printf_s("getaddrinfo failed with error: %d\n", iResult); 
     WSACleanup(); 
     return 0; 
    } 
    printf_s("Resolve the server address and port complete\n"); 

    // Create a SOCKET for connecting to server 
    listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); 
    if (listenSocket == INVALID_SOCKET) 
    { 
     printf_s("socket failed with error: %ld\n", WSAGetLastError()); 
     freeaddrinfo(result); 
     WSACleanup(); 
     return 0; 
    } 
    printf_s("Create a SOCKET for connecting to server complete\n"); 

    // Setup the TCP listening socket 
    iResult = bind(listenSocket, result->ai_addr, (int)result->ai_addrlen); 
    if (iResult == SOCKET_ERROR) 
    { 
     printf_s("bind failed with error: %d\n", WSAGetLastError()); 
     freeaddrinfo(result); 
     closesocket(listenSocket); 
     WSACleanup(); 
     return 0; 
    } 
    freeaddrinfo(result); 
    iResult = listen(listenSocket, SOMAXCONN); 
    if (iResult == SOCKET_ERROR) 
    { 
     printf_s("listen failed with error: %d\n", WSAGetLastError()); 
     closesocket(listenSocket); 
     WSACleanup(); 
     return 0; 
    } 
    printf_s("Setup the TCP listening socket complete\n"); 

    // Continuously accept a client socket 
    std::thread l(Communication::AcceptClients); 
    l.detach(); 
    printf_s("Continuously accept a client socket running...\n"); 

    return 1; 
} 

void WINAPI Communication::AcceptClients() 
{ 
    SOCKADDR_IN client_info = { 0 }; 
    int addrsize = sizeof(client_info); 
    while (true) 
    { 
     connectSocket = accept(listenSocket, (struct sockaddr*)&client_info, &addrsize); 
     while (connectSocket == SOCKET_ERROR) 
      connectSocket = accept(listenSocket, (struct sockaddr*)&client_info, &addrsize); 
     char *IP = inet_ntoa(client_info.sin_addr); 
     printf_s("accept from %s complete\n", IP); 

     std::thread a(Communication::Receive); 
     a.detach(); 
    } 
} 

void WINAPI Communication::Receive() 
{ 
    int iResult; 
    char receiveBuffer[512]; 
    do 
    { 
     iResult = recv(connectSocket, receiveBuffer, 512, 0); 
     if (iResult == SOCKET_ERROR) 
     { 
      printf("recv failed with error: %d\n", WSAGetLastError()); 
      closesocket(connectSocket); 
      WSACleanup(); 
      return; 
     } 
     if (iResult < 512) 
      receiveBuffer[iResult] = '\0'; 
     else 
      receiveBuffer[512] = '\0'; 
     if (iResult > 0) 
     { 
      printf_s("Bytes received: %i - Data received: %s\n", iResult, receiveBuffer); 
      printf_s("Data Received: %s\n", receiveBuffer); 
     } 
     else if (iResult == 0) 
     { 
      printf_s("Connection closed\n"); 
      closesocket(connectSocket); 
      WSACleanup(); 
      return; 
     } 
     else 
     { 
      printf_s("recv failed with error: %d\n", WSAGetLastError()); 
      closesocket(connectSocket); 
      WSACleanup(); 
      return; 
     } 
    } while (iResult > 0); 

    // cleanup 
    closesocket(connectSocket); 
    WSACleanup(); 
} 

int Communication::Connect(PCSTR hostname, PCSTR port) 
{ 
    WSADATA wsaData; 
    SOCKET connectSocket = INVALID_SOCKET; 
    struct addrinfo *result = NULL, *ptr = NULL, hints; 
    int iResult; 

    // Initialize Winsock 
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); 
    if (iResult != 0) { 
     printf("WSAStartup failed with error: %d\n", iResult); 
     return 0; 
    } 
    printf("Initialize Winsock complete\n"); 

    ZeroMemory(&hints, sizeof(hints)); 
    hints.ai_family = AF_UNSPEC; 
    hints.ai_socktype = SOCK_STREAM; 
    hints.ai_protocol = IPPROTO_TCP; 

    // Resolve the server address and port 
    iResult = getaddrinfo(hostname, port, &hints, &result); 
    if (iResult != 0) { 
     printf("getaddrinfo failed with error: %d\n", iResult); 
     WSACleanup(); 
     return 0; 
    } 
    printf("Resolve the server address and port complete\n"); 

    // Attempt to connect to an address until one succeeds 
    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) { 
     // Create a SOCKET for connecting to server 
     connectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); 
     if (connectSocket == INVALID_SOCKET) { 
      printf("socket failed with error: %ld\n", WSAGetLastError()); 
      WSACleanup(); 
      return 0; 
     } 
     printf("Create a SOCKET for connecting to server complete\n"); 

     // Connect to server. 
     iResult = connect(connectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); 
     if (iResult == SOCKET_ERROR) { 
      closesocket(connectSocket); 
      connectSocket = INVALID_SOCKET; 
      continue; 
     } 
     printf("Connect to server complete\n"); 
     break; 
    } 
    freeaddrinfo(result); 
    if (connectSocket == INVALID_SOCKET) { 
     printf("Unable to connect to server!\n"); 
     WSACleanup(); 
     return 0; 
    } 
    printf("Attempt to connect to an address until one succeeds complete\n"); 

    std::string tempIP = hostname; 
    char *IP = new char[tempIP.length() + 1]; 
    strcpy(IP, tempIP.c_str()); 

    // Receive until the peer closes the connection 
    std::thread c(Communication::Receive); 
    c.detach(); 
    printf("Receive until the peer closes the connection running...\n"); 

    return 1; 
} 

int Communication::Send(std::string text) 
{ 
    char *sendBuffer = new char[text.length() + 1]; 
    strcpy(sendBuffer, text.c_str()); 

    // Send text 
    int iResult; 
    iResult = send(connectSocket, sendBuffer, (int)strlen(sendBuffer), 0); 
    if (iResult == SOCKET_ERROR) { 
     printf("send failed with error: %d\n", WSAGetLastError()); 
     closesocket(connectSocket); 
     WSACleanup(); 
     return 0; 
    } 

    printf("Bytes Sent: %ld - Data Sent: %s\n", iResult, sendBuffer); 
    return 1; 
} 

ответ

0

Каждый класс имеет скрытый параметр this. Вы не можете передавать свою функцию-член как функцию потока.

Смежные вопросы