Sign in to follow this  
Dragon707

[CPP] tcp Client _beginthread

Recommended Posts

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:
[code]SOCKET sock;[/code]
but why ? Do i need to set my sock; to static ?
networksession.cpp
[code]
#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));
}
[/code]

networksession.h
[code]
#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;
};
};

[/code]

Full code: [url="http://code.google.com/p/cpp-tcpclient/source/browse/trunk/"]http://code.google.c...e/browse/trunk/[/url]

Thank you !

[b][ PS: Sorry for my weak English, i am Dutch hehheh.. ][/b]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this