I've created a class named "TextMessage" that have a packet structure.Here is:
Code: Select all
class TextMessage
{
public:
static const int MAXSIZE = 508;
static const int HEADER_SIZE = 4;
//virtual bool validate() = 0;
//virtual void execute() = 0;
TextMessage()
{
m_pData=new char[MAXSIZE+HEADER_SIZE];
ZeroMemory(m_pData,MAXSIZE+HEADER_SIZE);
}
~TextMessage()
{
delete[] m_pData;
}
virtual bool validate()
{
bool validazione = true;
if(this->m_pDataSize > MAXSIZE + HEADER_SIZE)
validazione = false;
if(this->m_usID != 1)
validazione = false;
return validazione;
}
void init(char* p_str)
{
/*Id=0;
size=0;*/
//size=p_sizemsg;
unsigned short ID = 1;
unsigned short* p_addr=(unsigned short*)&m_pData[0];
*p_addr=ID;
m_pDataSize=strlen(p_str);
unsigned short* p_size=(unsigned short*)&m_pData[2];
*p_size=m_pDataSize;
memcpy(&m_pData[4],p_str,m_pDataSize);
}
void Load()
{
}
char* GetBuffer(int pos)
{
return &m_pData[pos];
}
int GetPacketSize()
{
return m_pDataSize+HEADER_SIZE;
}
void ReadID()
{
unsigned short* pIDAddr = ((unsigned short*)&m_pData[0]);
this->m_usID = *pIDAddr;
}
void ReadSize()
{
unsigned short* pSize = ((unsigned short*)&m_pData[2]);
this->m_pDataSize=*pSize;
}
protected:
char* m_pData;
int m_pDataSize;
unsigned short m_usID;
};
Code: Select all
#include <string>
#include "stdafx.h"
#include "PacketMessage.h"
using namespace std;
void Funct()
{
WSACleanup();
}
int main()
{
WSAData wData;
WSAStartup(MAKEWORD(2,2), &wData);
DWORD dwRes;
SOCKET g_hlistner = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sockaddr_in wAddress;
wAddress.sin_family=AF_INET;
wAddress.sin_port=htons(5000);
wAddress.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
int err=connect(g_hlistner,(sockaddr*)&wAddress ,sizeof(sockaddr_in)) ;
if (err==SOCKET_ERROR)
{
dwRes=GetLastError();
return -1;
}
//char* pp=new char[512];
string input;
string command="/quit";
TextMessage* Packet=new TextMessage();
char* ch=new char[512];
while(true)
{
cout <<"> ";
getline(cin,input);
Packet->init(strcpy(ch,input.c_str()));
//Packet->ReadID();
//Packet->ReadSize();
send(g_hlistner, Packet->GetBuffer(0), 512, 0);
if (input.compare(command)==0)
break;
}
atexit(Funct);
}
When i'm sending "Packet" in the Server class , the sended data(Packet->GetBuffer return the address of the string in Packet) is null(I think)
The code of the Server that must retrieve the Packet is this:
Code: Select all
char* tmp=new char[512];
Connection* thCon=(Connection*)pParam;
TextMessage* Packet=new TextMessage();
Packet->init(tmp);
int ISize=recv(thCon->m_pSocket, Packet->GetBuffer(0), Packet->HEADER_SIZE, NULL);
/*Packet.Id=(unsigned short)ISize;
Packet.size=(unsigned short)((short*)&ISize)[2];*/
Packet->ReadID();
Packet->ReadSize();
if (Packet->validate()==false)
{
int ISize=recv(thCon->m_pSocket, Packet->GetBuffer(4), Packet->GetPacketSize(), NULL);
thCon->m_pServer->DispatchAll(Packet->GetBuffer(4));
Help me thx