C++ Clientless - Recv Packets/Help

04/18/2014 21:09 meak1#1
Rly often it happends that 2 or more Recv packets get stored into one..
so i get 2 Packets in one.

I need to sync or is something wrong with the Code ?
Thanks for help(;

Code:
int _ConnectIt(void * unused)
{
	printf("Connecting to 222.111.x.x - xxx!\n");
	long rc;
	SOCKADDR_IN addr;

	rc=startWinsock();
	memset(&addr,0,sizeof(SOCKADDR_IN)); 
	addr.sin_family=AF_INET;
	addr.sin_port=htons(30001); 
	addr.sin_addr.s_addr=inet_addr("222.111.x.x");

	if(rc!=0) {
		printf("Fehler: startWinsock, fehler code: %d\n",rc);
		return 1;
	}
	else {
		printf("Winsock gestartet!\n");
	}
	s=socket(AF_INET,SOCK_STREAM,0);
	if(s==INVALID_SOCKET){
		printf("Fehler: Der Socket konnte nicht erstellt werden, fehler code: %d\n",WSAGetLastError());
		return 1;
	}
	else{
		printf("Socket erstellt!\n");
	}

	if(!connect(s,(SOCKADDR*)&addr,sizeof(SOCKADDR))){
		printf("Verbunden mit ...\n");

		while(true)
		{
			if(!_Get_Recv())
				break;	
if(buf[2] == 0x2A){
				printf("Server Response, to Generate AESKey/Sync etc\n");
}
}
}
Code:
#define DEFAULT_BUFLEN 1024
char* buffer= (char*) malloc(1024);
int iResult, data;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
char* buf;

bool _Get_Recv()
{
	char recvbuf[DEFAULT_BUFLEN];
	int recvbuflen = DEFAULT_BUFLEN;

	while(true){
		iResult = recv(s, recvbuf, recvbuflen, 0);

		if ( iResult > 0 ){
			printf("Bytes received: %d\n", iResult);
                        buf=recvbuf;
			return true;
		}else if ( iResult == 0 ){
			printf("Connection closed\n");
			system("PAUSE");
		}else{
			printf("recv failed: %d\n", WSAGetLastError());
			system("PAUSE");
		}
	}
}
04/18/2014 21:18 Actidnoide#2
TCP is a stream based protocol. It's not frame based so you can't be sure wether your data arrives in one or splitted. You need to store the data in a buffer and implement a protocol which gives information about packet boundaries.

like:
Code:
while(recvdata()){
 // append data to buffer
...

    if (bufferContainsCompletePacket)
    {
        // pull out packet and handle
        ...
    }
}
Further help:
[Only registered and activated users can see links. Click Here To Register...]
04/19/2014 14:41 meak1#3
ok, so the Code is correct and i just need to do an Filter?

like ->

Code:
if(buf[0] > iResult){ //buf[0] <- is the Packet Size in the Game.
-> Split Packet
}
Correct? i thought i could sync or smth, that it not get stored into one buffer(; - but as u said its Stream based :b
04/19/2014 15:01 Actidnoide#4
iResult only represents the amount of data received in one recv() call.
More like:

Code:
// curDataSize -> length of data received from recv()
if (curDataSize >= buf[0]){
-> Split Packet
}
So the first byte indicates the packet length.

But remember that a signed char (buf[i]) only allows a range from -128 to 127.
04/19/2014 17:49 meak1#5
i know, i would do an *(WORD*)&buf[0]; ;> Thanks anyway(;
trying it later ;E