Jump to content
  • Advertisement
Sign in to follow this  
Dragon707

[CPP] tcp Client _beginthread

This topic is 2447 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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:
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.. ]

Share this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!