Jump to content

  • Log In with Google      Sign In   
  • Create Account

[C++, eNet] Sending player state client <=> server


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 SeaMonster131   Members   -  Reputation: 107

Like
0Likes
Like

Posted 06 November 2013 - 09:37 AM

Hi, I'm writing mmorpg game and I've got a problem. I spent a lot of time looking for some tips, but I found nothing.

 

If there is one player in the game, it's okay. But if there are more players, they move in sequence in the order in which they moved. Each client sends the position of the player in normal function, and receives it in function on another thread. If I try to make a second thread on the server (only to receive position), the client has about 10 fps (normally 60).

 

Client - main.cpp

while(1) {
...
        if(ev.type == ALLEGRO_EVENT_TIMER){ // 60 fps
...
                /*** LOGIC ***/
                player->update(key);

                _beginthread(player_updatePos, 0, player);

        }

Client - player.cpp

// - send pos
void CPlayer::update(CKeyboard key) {
    ++timeToSend;

    if(timeToSend >= 1/* && (oldPos.x != pos.x || oldPos.y != pos.y)*/) { //  [ 20 = 1/3 sec with 60 FPS ]
        timeToSend = 0;

        // send position
        char wiad[45] = "";

        char buf[10];
        itoa(pos.x, buf, 10);
        char buf2[10];
        itoa(pos.y, buf2, 10);

        char buf4[20];
        itoa(nick.size(), buf4, 10);

        char* buf3 = new char[nick.size()];
        for(int i = 0; i < nick.size(); ++i)
            buf3[i] = nick[i];

        sprintf(wiad, "POS%s%s=%sx%s", buf4, buf3, buf, buf2);

        sendToServerUnseq(wiad, 1);
    }
}

// - receive pos
void __cdecl player_updatePos(void* arg) {
//void player_updatePos(CPlayer* player) {

    CPlayer* player = static_cast<CPlayer*>(arg);

    if(event.type == ENET_EVENT_TYPE_RECEIVE) {

        if(receive(event.packet->data, "POS")) {
            string mes = getPacket(event.packet->data);
            
...
            if(nickInnego != player->nick)
            {
                bool finded = false;
                for(int i = 0; i < v_otherPlayers.size(); ++i) {
                    if(v_otherPlayers[i].nick == nickInnego) {
                        v_otherPlayers[i].pos.x = atoi(posX.c_str());
                        v_otherPlayers[i].pos.y = atoi(posY.c_str());
                        v_otherPlayers[i].timeFromLastReceive = 0;
                        finded = true;
                        break;
                    }
                }
                if(!finded) { // new player
                    v_otherPlayers.push_back(COtherPlayer(nickInnego));
                }
            }
            else
                player->oldPos = player->pos;
        }
    }

    _endthread();
}

Client - function to send position

void sendToServerUnseq(char* message, int channelID) {
    ENetPacket *p = enet_packet_create((char*)message, strlen(message)+1, ENET_PACKET_FLAG_UNSEQUENCED);
    enet_peer_send(peer, channelID, p);

    enet_host_flush(client);

    serviceResult = enet_host_service(client, &event, 100);
}

Server - main.cpp (it's only sends that, he got from the client)

while(1)
{
serviceResult = enet_host_service(server, &event, 1); //1000 = 1 sec


case ENET_EVENT_TYPE_RECEIVE:
{
if(receive(event.packet->data, "POS")) {
                        char mess[event.packet->dataLength];

                        for(int i = 0; i < event.packet->dataLength; ++i)
                            mess[i] = event.packet->data[i];

                        ENetPacket *p = enet_packet_create(mess, strlen(mess)+1, ENET_PACKET_FLAG_UNSEQUENCED);

                        enet_host_broadcast(server, 1, p);
                        enet_host_flush(server);
                    }
}
}

What is wrong? Thanks for any help! :)



Sponsor:

#2 0BZEN   Crossbones+   -  Reputation: 2016

Like
1Likes
Like

Posted 19 November 2013 - 08:52 AM

dont use sprintf, it's unsafe. use sprintf_s, or whatever the bound checked version is.

 

As for your problem, I can't say at a glance. Looks like you'll have to get better at debugging. Print out what data goes out, what data comes in, into the console, or a file, put breakpoints, and just step through the code.

 

Here's a simpler way to generate packets.

char packet[256];
int packetlen = sprintf_s(packet, sizeof(packet), "POS%d%s=%dx%d", nick.size(), (const char*)nick[0], pos.x, pos.y);

Finally, I would refrain from using that sort of verbose format, and use some form of binary serialisation, or some other library that will give you the opportunity to format, and parse text strings more efficiently.

 

 

Or if you want some readable packet, for debugging, 'tokenise' the string. Much easier to digest on the other end.

char packet[256];
int packetlen = sprintf_s(packet, sizeof(packet), "msgid=%s, player=%s, posx=%d, posy=%d", "POS", (const char*)nick[0], pos.x, pos.y);

Edited by papalazaru, 19 November 2013 - 08:52 AM.

Everything is better with Metal.


#3 rip-off   Moderators   -  Reputation: 8206

Like
2Likes
Like

Posted 19 November 2013 - 11:43 AM

You should not be spawning threads like that. Threads are relatively expensive objects to create. If you need any threading at all, a single extra networking thread should be able to comfortably handle all your networking needs (networking is I/O limited).

 

Another issue is that you do not appear to be using synchronisation to control access to shared memory. This may appear to work, but you cannot depend on it doing so and if it doesn't occasionally break already it certainly will in some real world scenario. You probably don't need to use any threads at all for this, and you probably shouldn't be using them either. Threading is a very complex, subtle and somewhat black art. If you find you need to use threading I'd recommend dedicating some time to learning how threading works by reading some good books on the subject, and separate any such learning from any ongoing projects you have.

 

Your code also leaks memory and may be vulnerable to buffer overflow attacks. In a network facing server or client, a buffer overflow attack could easily result in the remote peer being able to execute arbitrary code as the running user. Try to avoid using raw pointers and manual memory management at all. Using std::string and std::vector where possible. For networking, you probably also want to add sanity checking to any data received, paying particularly careful attention to where variable length data is allowed.

 

Another flaw in your current code is that the client specifies the nickname in the packet, and you appear to be using nicknames to determine which object to apply the position to. Thus, if I wrote a malicious client, I can specify that I am moving someone else's character. The server should be enforcing this - clients should register a unique nickname with the server when the connection is first being established. From then on, the server should assume that any messages coming from that remote peer belong to that nickname. So the client doesn't need to send it's nickname with each message, the server can prefix each forwarded message with the nickname of the appropriate client.

 

Ideally, the server would be running a copy of the game logic too, and would detect and reject any cheating attempts (such as movements between two points exceeding the player's maximum speed, or movement that would not be possible due to intervening obstacles).

 

Note also that decoupling messages from the user's nickname is probably a good idea - the protocol could instead specify player "ID" integers. The server can generate a unique player ID when new connections are established. This will be more efficient and also avoids certain edge cases such as a user wishing to change nickname in the middle of the game. But you can change this later on if necessary, it isn't quite as important as some of the other details.

 

I strongly advise removing threading from your game for the time being.


Edited by rip-off, 19 November 2013 - 11:44 AM.


#4 SeaMonster131   Members   -  Reputation: 107

Like
0Likes
Like

Posted 25 November 2013 - 08:11 AM

Thanks very much for answers. For now, I'll try to do a smaller network project, but using your advices. At the beginning I didn't know that network programming is so difficult :)






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS