gpt4 book ai didi

带线程的 C++ 网络类

转载 作者:太空宇宙 更新时间:2023-11-04 13:55:45 25 4
gpt4 key购买 nike

我正在尝试让我根据 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"

通过谷歌阅读,我发现在类内部创建线程时应该使用静态函数;但是在实现这个时,我似乎无法为该类的实例分配 connectSocket、listenSocket 和 *IP。我希望能够使用它们,以便可以使用 client.Send()。我知道 server.Send() 目前无法正常工作。我只想让客户先发送。

在不使用预建网络库的情况下,解决这个问题的实用方法是什么?

源代码.cpp

#include "Communication.h"

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

通讯.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);
};

通讯.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;
}

最佳答案

每个类函数调用都有一个隐藏参数this。您实际上不能将成员函数作为线程函数传递。

关于带线程的 C++ 网络类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21540510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com