About 4 month ago i started learning sdl2 to make simple games. I am familiar with all sdl family (sdl image, sdl ttf...). The thing is that now i want to implement multiplayer to my game, so i want to use SDL2Net. For the basics was fine, but i need to send vectors through packages, so i would need to implement serialization or a protocol buff, so i chose protobuf (Google Protocol Buff). My game was going to be like a snake but multiplater. So the client would send the position of his snake parts and the server would send the position of every client parts (and from himself, the server also plays). At start everything was fine but now i dond't know why i am getting error. I will leave part of source code where i get trouble:
"network.protobuf"
package network;
message PositionSnakePart {
required int32 pos_x = 1;
required int32 pos_y = 2;
}
message Snake
{
optional int32 id = 1;
repeated PositionSnakePart positionsnakepart = 2;
}
message FromServerToClient
{
required bool gameover = 1 [default = false];
repeated Snake snakes_game = 2;
}
"game.cpp"
void readVariables(network::FromServerToClient &from_server_to_client) {//Read data}
void readVariables(network::Snake snake_to_pass) {//Read data}
void addSnakeServer(network::FromServerToClient &from_server_to_client) {//Add snake and parts of snake}
void multiplayerServer(){
int buffer_zise = 200;
char buffer[buffer_zise];
bool quitClient = false;
network::FromServerToClient from_server_to_client;
...
//starts sdlnet and the connection with server and comes into loop
...
std::string StringToSerialize;
if (!from_server_to_client.SerializeToString(&StringToSerialize)) //Serialization ok
{
std::cout << "/* Failed to serialize */" << std::endl;
}
if (from_server_to_client.IsInitialized()) //All ok
{
std::cout << "All ok to send!" << std::endl;
}
std::cout << StringToSerialize.size() << std::endl; //To test, it was 22 at first, then 21 and then 20
SDLNet_TCP_Send(clientSocket, StringToSerialize.c_str(), StringToSerialize.size()); //Sending the package was alright
...
}
void multiplayerClient(){
int buffer_zise = 200;
char buffer[buffer_zise];
bool quitClient = false;
network::FromServerToClient other_players_snakes;
...
//starts sdlnet and the connection with server and comes into loop
...
int a = SDLNet_TCP_Recv( client, buffer, buffer_zise );
if (a <= 0)
{
std::cout << "Connection Broken" << std::endl;
quitClient = true; //If connection broken quit game
}
std::string StringToParse(buffer);
printf("bytes received:%d --- String in bytes:%d --- Char[] in bytes:%d\n", a, StringToParse.size(), strlen(buffer));
//There is the problem, i received 20 bytes with the function wich is ok (a=20), then the string StringToParse in bytes is 1 and the buffer in bytes is 1
if (!other_players_snakes.ParseFromString(StringToParse))
{
std::cout << "Failed to parse" << std::endl; //Obviusly this prints out
}
else
{
readVariables(other_players_snakes);
}
...
}