• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0

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

3 posts in this topic

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 ***/

                _beginthread(player_updatePos, 0, player);


Client - player.cpp

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

    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;
                if(!finded) { // new player
                player->oldPos = player->pos;


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);


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

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

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

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);

What is wrong? Thanks for any help! :)


Share this post

Link to post
Share on other sites

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

Share this post

Link to post
Share on other sites

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

Share this post

Link to post
Share on other sites

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 :)


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
Followers 0