[CPP] tcp Client _beginthread

Started by
0 comments, last by SiCrane 12 years, 6 months ago
Hello Gamedev.net !

I have a little question, i've have a problem with my CPP code. I have made a TCP class with threading.
So when i call the function ConnectTo(char* host, unsigned short port); it starts a thread to startup the connection. But the called threaded function must be static ???. I got the message 'Invalid use of member' in the networksession.h on line 20:
SOCKET sock;
but why ? Do i need to set my sock; to static ?
networksession.cpp

#include "networksession.h"

using namespace NetworkSession;

TcpClient::TcpClient()
{
std::cout << "TcpClient constructor!" << std::endl;
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,0), &wsaData)!=0)
{
throw "Could not startup WSA...";
}
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock==INVALID_SOCKET)
{
throw "Invalid socket...";
}
}

TcpClient::~TcpClient()
{
std::cout << "TcpClient deconstructor!" << std::endl;
WSACleanup();
}

void TcpClient::ConnectTo(char* host, unsigned short port)
{
NetworkData::sckAddr addr;
addr.host = host;
addr.port = port;
_beginthread(Thread_ConnecTo, NULL, (void*)&addr);
}

void TcpClient::Thread_ConnecTo(void* pParam)
{
NetworkData::sckAddr *addr = (NetworkData::sckAddr*)pParam;
sockaddr_in sckAddr;
sckAddr.sin_family = AF_INET;
sckAddr.sin_port = htons(addr->port);
sckAddr.sin_addr.S_un.S_addr = inet_addr(addr->host);
connect(sock, (sckAddr*)&sckAddr, sizeof(sckAddr));
}


networksession.h

#pragma once

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

namespace NetworkSession
{
class TcpClient
{
public:
TcpClient();
~TcpClient();
void ConnectTo(char* host, unsigned short port);

private:
static void Thread_ConnecTo(void* pParam);

private:
SOCKET sock;
};
};

namespace NetworkData
{
struct sckAddr
{
char* host;
unsigned short port;
};
};



Full code: http://code.google.c...e/browse/trunk/

Thank you !

[ PS: Sorry for my weak English, i am Dutch hehheh.. ]
Advertisement
In _beginthread(), the arglist parameter contains all the state that will be passed to the function. If you want to use the member variables of a particular class instance, pass the class instance as part of the structure in addition to other data the function needs. In your case, you could create a struct holds both a TcpClient * and a sckAddr.

This topic is closed to new replies.

Advertisement