Friday, August 12, 2016

Part 3: Multiplayer WebSocket Game server written in C using libuv & libwebsockets & Cocos2d-x-HTML5

In this file all the game logic is happening ,

  1. Start game loop timer.
  2. Establish the client connection.  
  3. The WebSocket request received from client connection.
  4. The connection is kept in hash map. 
  5. From the game loop response back to the client after processing the data.
  6. Updates other clients about the current client . 
Main assumptions on event driven servers , the requests must be received none stop and be able to none block it on any conditions,
Remember no threads here per connection .
Each request will call callback function that the server must handle asynchronously.
The client and the server have pre defined simple protocol which defined and inform both sides
about the state they are in .
This is the state protocol used in this tutorial :

0 : login
1 : login success acknowledgment
2 : send move request
3 : response move acknowledgment
4 : other player register
5 : other player movment
6 : delete user from client
7 : gem scatter
8 : gem eat and score increment 
9 : gem eat and score increment acknowledgment
game_handler.c 


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/*******************************************************
Copyright (C) 2016 meiry242@gmail.com
This file is part of http://www.gamedevcraft.com .
Author : Meir yanovich
********************************************************/

#include "game_handler.h"
#include "simplog.h"
extern int debug_level;
connection_num_as_id = 0;
Hashmap *users_map_main = NULL;
//Array *gems_array = NULL;
uv_timer_t timeout_watcher;
static bool str_eq(void *key_a, void *key_b)
{
 return !strcmp((const char *)key_a, (const char *)key_b);
}
/* use djb hash unless we find it inadequate */
static int str_hash_fn(void *str)
{
 uint32_t hash = 5381;
 char *p;

 for (p = str; p && *p; p++)
 {
  hash = ((hash << 5) + hash) + *p;
 }
 return (int)hash;
}
static int c = 0;
//generate random gems in the game 
bool generate_random_gems(int num_of_gems, gem_types gem_type)
{
 if (gems_array == NULL)
 {
  gems_array = arrayCreate();
 }
 int array_size = arraySize(gems_array);
 //960, 640 
   
 for (int i = array_size; i < (array_size+num_of_gems); i++)
 {
  struct gem_data *gemdata = malloc(sizeof * gemdata);
  //r = (rand() % (max + 1 - min)) + min
  int rw = (rand() % (900 + 1 - 50)) + 50; //returns a pseudo-random integer between x resolution size 0 -> width
  int rh = (rand() % (600 + 1 - 50)) + 50;    //returns a pseudo-random integer between x resolution size 0 -> height
  lwsl_notice("c:%d type:%d width %d height %d\n", c, gem_type, rw, rh);
  gemdata->type = gem_type;
  gemdata->x = rw;
  gemdata->y = rh;
  gemdata->collide_with_player = false;
  arrayAdd(gems_array, gemdata);
  c++;
 }
 return true;
}

struct session_holder_data * set_session_holder_data(bool(*cp)(void*, void*, void*),
              struct per_session_data__apigataway *_pss)
{
 struct session_holder_data *session_holder_data_tmp = malloc(sizeof * session_holder_data_tmp);
 session_holder_data_tmp->found = false;
 session_holder_data_tmp->current_session_player_id = _pss->player_id;
 session_holder_data_tmp->players_session_holder = arrayCreate();
 hashmapForEach(users_map_main, cp, session_holder_data_tmp);
 return session_holder_data_tmp;
}

void send_response(cJSON *_root_respose,struct per_session_data__apigataway *_other_p_session,
             struct per_session_data__apigataway *_pss)
{
 unsigned char response_to_other_client[LWS_PRE + 1024];
 unsigned char *p_response_to_other_client = &response_to_other_client[LWS_PRE];
 char* resp_json = cJSON_Print(_root_respose);
 int n = sprintf((char *)p_response_to_other_client, "%s", resp_json);
    lwsl_notice("send_response to client [%s]  %s\n", _other_p_session->player_name, resp_json);
    LOG_PRINT("send_response to client [%s]  %s\n", _other_p_session->player_name, resp_json);
 //lwsl_notice("[%s] send response to client [%s] from server on registrator: %s \n", _pss->player_name, _other_p_session->player_name, p_response_to_other_client);
 //LOG_PRINT("[%s] send response to client [%s] from server on registrator: %s \n", _pss->player_name, _other_p_session->player_name, p_response_to_other_client);
 //each player has its own copy of libwebsockets (lws in short ) wsi , whitch is the player channel + session pointer 
 int m = lws_write(_other_p_session->player_wsi, p_response_to_other_client, n, LWS_WRITE_BINARY);
 if (m < n) {
  lwsl_err("ERROR %d writing to di socket on registrator\n", sizeof(response_to_other_client));
  LOG_PRINT("ERROR %d writing to di socket on movment\n", sizeof(response_to_other_client));
 }
}
//preper inform about this user which is dead ( disconnected from the game ) 
static bool user_is_dead_cp(void* key, void* value, void* context)
{
 struct session_holder_data *session_holder_data_tmp =
  (struct session_holder_data *)context;
 //It is not the current user 
 //lwsl_notice("key: '%s' current_session_player_id: '%s'\n", (char *)key, (char *)session_holder_data_tmp->current_session_player_id);
 if (strcmp(key, session_holder_data_tmp->current_session_player_id) != 0)
 {
  //set the holder 
  arrayAdd(session_holder_data_tmp->players_session_holder, (struct per_session_data__apigataway *)value);
 }
 return true;
}
//check and handle other users
static bool check_other_users_cp(void* key, void* value, void* context)
{
 struct session_holder_data *session_holder_data_tmp =
  (struct session_holder_data *)context;
 //It is not the current user 
 //lwsl_notice("key: '%s' current_session_player_id: '%s'\n", (char *)key, (char *)session_holder_data_tmp->current_session_player_id);
 if (strcmp(key, session_holder_data_tmp->current_session_player_id) != 0)
 {
  //set the holder 
  arrayAdd(session_holder_data_tmp->players_session_holder, (struct per_session_data__apigataway *)value);
 }
 return true;
}
//check and handle other movments
static bool check_other_users_movment_cp(void* key, void* value, void* context)
{
 struct session_holder_data *session_holder_data_tmp =
  (struct session_holder_data *)context;
 //It is not the current user 
 //lwsl_notice("key: '%s' current_session_player_id: '%s'\n", (char *)key, (char *)session_holder_data_tmp->current_session_player_id);
 //LOG_PRINT("key: '%s' current_session_player_id: '%s'\n", (char *)key, (char *)session_holder_data_tmp->current_session_player_id);
 if (strcmp(key, session_holder_data_tmp->current_session_player_id) != 0)
 {
  //set the holder 
  arrayAdd(session_holder_data_tmp->players_session_holder, (struct per_session_data__apigataway *)value);
 }
 return true;
}
//check and handle other score update
static bool check_other_users_gemscore_cp(void* key, void* value, void* context)
{
 struct session_holder_data *session_holder_data_tmp =
  (struct session_holder_data *)context;
 //It is not the current user 
 //lwsl_notice("key: '%s' current_session_player_id: '%s'\n", (char *)key, (char *)session_holder_data_tmp->current_session_player_id);
 //LOG_PRINT("key: '%s' current_session_player_id: '%s'\n", (char *)key, (char *)session_holder_data_tmp->current_session_player_id);
 if (strcmp(key, session_holder_data_tmp->current_session_player_id) != 0)
 {
  //set the holder 
  arrayAdd(session_holder_data_tmp->players_session_holder, (struct per_session_data__apigataway *)value);
 }
 return true;
}

//response to every 100ms game loop tick
static bool response_to_client_cp(void* key, void* value, void* context)
{
 bool doInvokeResponse = false;
 int hash_map_size = hashmapSize(users_map_main); 
  
 if (hash_map_size > 0)
 {
  //when response is created there is need to define buffer to hold the response 
  //libwebsokets way there need for pedding left:LWS_PRE  
  struct per_session_data__apigataway *pss =
   (struct per_session_data__apigataway *)hashmapGet(users_map_main, (char *)key);
        char* resp_jsont = cJSON_Print(pss->user_json_respose);
        //lwsl_notice("INSIDE RESPONSE_TO_CLIENT_CP pss->user_json_respose: %s \n", resp_jsont);
        //LOG_PRINT("INSIDE RESPONSE_TO_CLIENT_CP pss->user_json_respose: %s \n", resp_jsont);
  //first on registretion the server scatter the gems 
  if (pss->status == 0 && pss->done_srv_update == true)
  {  
   cJSON *root_respose = build_gems_scatter_json(pss);
   doInvokeResponse = true;
   pss->user_json_respose = root_respose;
   char* resp_json = cJSON_Print(pss->user_json_respose);
   lwsl_notice("Response to client gems from server: %s \n",resp_json);
   send_response_to_current_player(pss);
  }
  //response json by state of the user
  //state 1 registretion :
  if (pss->status == 0 && pss->done_srv_update == true)
  {
   //update it to 1 so registretion will invoked only once per conneting user
   pss->status =1;
   cJSON *root_respose = build_player_json_registrator(pss);
   doInvokeResponse = true;
   //check if there is other players that registed beside you
   int user_hash_size = hashmapSize(users_map_main);
   //lwsl_notice("response_to_client_cp : user_hash_size: %d \n", user_hash_size);
   if (user_hash_size > 1)
   {
    struct session_holder_data *session_holder_data_tmp = set_session_holder_data(check_other_users_cp, pss);
    //now we have the others users which we need to update the current user     
    //preper the other players session structures 
    cJSON* players;
    int i = 0;
    int size = arraySize(session_holder_data_tmp->players_session_holder);
    if (size > 0)
    {
     players = cJSON_CreateArray();
     while (i < size) {
      struct per_session_data__apigataway *other_p_session = arrayGet(session_holder_data_tmp->players_session_holder, i);
      //build json of player 
      cJSON* player = build_player_json_registrator(other_p_session);
      cJSON_InsertItemInArray(players, i, player);
      //send current player to other players 
      //change only for this response the json to: "4 : other player"
      int status = cJSON_GetObjectItem(root_respose, "status")->valueint;
      //BUG in cJSON need to update also valuedouble when updating valueint
      //https://sourceforge.net/p/cjson/discussion/998969/thread/813ba29b/
      cJSON_GetObjectItem(root_respose, "status")->valueint = 4; 
      cJSON_GetObjectItem(root_respose, "status")->valuedouble = 4;
      //send to client 
      send_response(root_respose,other_p_session,pss);
      //set back the original status
      cJSON_GetObjectItem(root_respose, "status")->valueint = status;
      cJSON_GetObjectItem(root_respose, "status")->valuedouble = status;
      // Move to next.
      i++;
      
     }
     cJSON_AddItemToObject(root_respose, "players", players);
     arrayFree(session_holder_data_tmp->players_session_holder);
     free(session_holder_data_tmp);
    }
   }
   pss->user_json_respose = root_respose;   
  }
  else if (pss->status == 2 &&  pss->done_srv_update == true) //movment state
  {
           
   pss->status =3; //aprove movment state 
   //for current session 
   doInvokeResponse = true;
   cJSON *root_respose = build_player_json_movment(pss);
            //lwsl_notice("RESPONSE START pss->request_from_client_buf Movment 2: %s \n", pss->request_from_client_buf);
            //LOG_PRINT("RESPONSE START pss->request_from_client_buf Movmente 2: %s \n", pss->request_from_client_buf);
            if (pss->collision_status == 8)
            {
                //gem eat and score increment acknowledgment
                pss->collision_status = 9;
                root_respose = build_gems_score_json(pss);
                lwsl_notice("RESPONSE MIDELL pss->collision_status: %d \n", pss->collision_status);
                LOG_PRINT("RESPONSE MIDELL pss->collision_status: %d \n", pss->collision_status);
            }
            //lwsl_notice("RESPONSE pss->request_from_client_buf Movment 2: %s \n", pss->request_from_client_buf);
            //LOG_PRINT("RESPONSE pss->request_from_client_buf Movmente 2: %s \n", pss->request_from_client_buf);
   int user_hash_size = hashmapSize(users_map_main);
   //lwsl_notice("response_to_client_cp : user_hash_size: %d \n", user_hash_size);
   if (user_hash_size > 1)
   {
    //create tmp game users session data holder 
    struct session_holder_data *session_holder_data_tmp = set_session_holder_data(check_other_users_movment_cp, pss);
    int i = 0;
    //check if there are more users then current player 
    int size = arraySize(session_holder_data_tmp->players_session_holder);
    if (size > 0)
    {     
     while (i < size) 
     {
      struct per_session_data__apigataway *other_p_session = arrayGet(session_holder_data_tmp->players_session_holder, i);
      //send current player to other players 
      //change the status only for this response the json status param to: "4 : other player"
      int status = cJSON_GetObjectItem(root_respose, "status")->valueint;
      //BUG in cJSON need to update also valuedouble when updating valueint
      //https://sourceforge.net/p/cjson/discussion/998969/thread/813ba29b/
      cJSON_GetObjectItem(root_respose, "status")->valueint = 5;
      cJSON_GetObjectItem(root_respose, "status")->valuedouble = 5;
      char* resp_json = cJSON_Print(root_respose);
      //send to client
      send_response(root_respose, other_p_session, pss);
      //set back the original status
      cJSON_GetObjectItem(root_respose, "status")->valueint = status;
      cJSON_GetObjectItem(root_respose, "status")->valuedouble = status;
      // Move to next.
      i++;
     }
     //clean 
     arrayFree(session_holder_data_tmp->players_session_holder);
     free(session_holder_data_tmp);
    }
   }
   //save the letest response 
   pss->user_json_respose = root_respose;
  }       
  //now invoke to the current session of the current player
  if (doInvokeResponse)
  {
   send_response_to_current_player(pss);
  }
 }
 return true;
}
//send respomse to current session player
void send_response_to_current_player(struct per_session_data__apigataway *_pss)
{
 unsigned char response_to_client[LWS_PRE + 1024];
 unsigned char *p_response_to_clientout = &response_to_client[LWS_PRE];
 char* resp_json = cJSON_Print(_pss->user_json_respose);
 int n = sprintf((char *)p_response_to_clientout, "%s", resp_json);
 //lwsl_notice("Response to client from server: %s \n", p_response_to_clientout);
 //LOG_PRINT("Response to client from server: %s \n", p_response_to_clientout);
 //each player has its own copy of libwebsockets (lws in short ) wsi , witch is the player channel + session pointer 
 int m = lws_write(_pss->player_wsi, p_response_to_clientout, n, LWS_WRITE_BINARY);
 if (m < n) {
  lwsl_err("ERROR %d writing to di socket\n", sizeof(response_to_client));
  LOG_PRINT("ERROR %d writing to di socket\n", sizeof(response_to_client));
 }
 //reset values for next tick in the game loop 
 memset(_pss->player_seq, 0, sizeof(_pss->player_seq));
 _pss->player_seq_index = 0;
    _pss->collision_status = 0;
}
//scatter the gems 
void scatter_gems()
{
 generate_random_gems(1, SIMPLE);
 //generate_random_gems(3, BOMB);
}
//all sessions to the game will be invoked via this function 
//this function is the GAME LOGIC 
static void game_loop_cb(uv_timer_t* handle
#if UV_VERSION_MAJOR == 0
 , int status
#endif
 ) {
  
 ASSERT(handle != NULL);
 ASSERT(1 == uv_is_active((uv_handle_t*)handle));
  
 int after = hashmapSize(users_map_main);
 if (hashmapSize(users_map_main)>0)
 {
  hashmapForEach(users_map_main, &response_to_client_cp, users_map_main);
 }

}
//main ws api function , which is called each time client invoke API 
int callback_wsapi(struct lws *wsi, enum lws_callback_reasons reason,
     void *user, void *in, size_t len)
{
 if (users_map_main == NULL)
 {
  users_map_main = hashmapCreate(10, str_hash_fn, str_eq);
 }
 //char *resp_json;
 unsigned char response_to_client[LWS_PRE + 1024];
 struct per_session_data__apigataway *pss =
  (struct per_session_data__apigataway *)user;
 unsigned char *p_response_to_clientout = &response_to_client[LWS_PRE];
 int n;
 
  switch (reason) {
  case LWS_CALLBACK_PROTOCOL_INIT:
  {
   srand((unsigned int)time(NULL));
   //Scatter gems
   scatter_gems();
   uv_timer_init(lws_uv_getloop(lws_get_context(wsi), 0),&timeout_watcher);
   //every 100ms
   uv_timer_start(&timeout_watcher, game_loop_cb, 1000, 100);
   break;
  }
  case LWS_CALLBACK_ESTABLISHED:
  {
   pss->recive_all_from_client = 0;
   pss->player_wsi = malloc(sizeof pss->player_wsi);
   pss->player_wsi = wsi;
   pss->player_seq_index = 0;
   pss->score = 0;
   pss->bomb_gems = arrayCreate();
   pss->simple_gems = arrayCreate();
   connection_num_as_id++;
   break;
  }
  case LWS_CALLBACK_SERVER_WRITEABLE:
  {
    //get request from client and parse json     
    //lwsl_notice("pss->request_from_client_buf 2: %s \n", pss->request_from_client_buf);
    cJSON * root = cJSON_Parse(pss->request_from_client_buf);
    int status = cJSON_GetObjectItem(root, "status")->valueint;
    switch (status) {
     case 0: //Registration
     { 
      pss->done_srv_update = false;
      pss->player_name = cJSON_GetObjectItem(root, "player_name")->valuestring;
      pss->status = status;
      pss->player_id = generateId();
      pss->utc_timestemp = (long long)time(NULL);
      char* end_player_pos_x = cJSON_GetObjectItem(root, "end_player_pos_x")->valuestring;
      char* end_player_pos_y = cJSON_GetObjectItem(root, "end_player_pos_y")->valuestring;
      pss->end_player_pos_x = end_player_pos_x;
      pss->end_player_pos_y = end_player_pos_y;
      pss->done_srv_update = true;      
      //set the user in the users repostory on succesfull registretion
      hashmapPut(users_map_main, pss->player_id, pss);
      int after = hashmapSize(users_map_main);
      lwsl_notice("Registration : hashmapSize size :%d ,  \n", after);
      break;
     }
     case 2: //Movment
     { 
      //MEIRY need to update hashmap
                        lwsl_notice("pss->request_from_client_buf Movment : %s \n", pss->request_from_client_buf);
                        LOG_PRINT("pss->request_from_client_buf Movmente : %s \n", pss->request_from_client_buf);
      pss->done_srv_update = false;
                        int collision_status = cJSON_GetObjectItem(root, "collision_status")->valueint;
                        pss->collision_status = collision_status;
      pss->counter++;
      //lwsl_notice("Movment : pss->player_seq_index :%d ,  \n", pss->player_seq_index);
      char* player_x = cJSON_GetObjectItem(root, "player_x")->valuestring;
      char* player_y = cJSON_GetObjectItem(root, "player_y")->valuestring;
      //lwsl_notice("Movmentplayer_x:%s\n", player_x);
      //lwsl_notice("Movmentplayer_y:%s\n", player_y);
      char* end_player_pos_x = cJSON_GetObjectItem(root, "end_player_pos_x")->valuestring;
      char* end_player_pos_y = cJSON_GetObjectItem(root, "end_player_pos_y")->valuestring;
      char* player_seq = cJSON_GetObjectItem(root, "player_seq")->valuestring;
      //int stop_player = cJSON_GetObjectItem(root, "stop_player")->valueint;
      int status = cJSON_GetObjectItem(root, "status")->valueint;
                        
      pss->player_x_r[pss->player_seq_index] = player_x;
      pss->player_y_r[pss->player_seq_index] = player_y;
      pss->player_seq[pss->player_seq_index] = player_seq;
      //lwsl_notice("Movment : pss->player_seq_index :%d ,  \n", pss->player_seq_index);
      pss->player_seq_index++;
      pss->status =2;  
                       
      pss->utc_timestemp = (long long)time(NULL); //for tracking
      pss->end_player_pos_x = end_player_pos_x;
      pss->end_player_pos_y = end_player_pos_y;
                        lwsl_notice("MIDEL pss->request_from_client_buf Movment : %s \n", pss->request_from_client_buf);
                        LOG_PRINT("MIDEL pss->request_from_client_buf Movmente : %s \n", pss->request_from_client_buf);
                        if (pss->collision_status == 8)
                        {
                            lwsl_notice("INSIDE 1 pss->request_from_client_buf Movment : %s \n", pss->request_from_client_buf);
                            LOG_PRINT("INSIDE 1 pss->request_from_client_buf Movmente : %s \n", pss->request_from_client_buf);
                            int score = cJSON_GetObjectItem(root, "score")->valueint;
                            cJSON *simple_gems = cJSON_GetObjectItem(root, "simple_gems");
                            for (int i = 0; i < cJSON_GetArraySize(simple_gems); i++)
                            {

                                struct gem_data *gemdata = malloc(sizeof * gemdata);
                                cJSON * itemX = cJSON_GetArrayItem(simple_gems, i);
                                ++i;
                                cJSON * itemY = cJSON_GetArrayItem(simple_gems, i);
                                gemdata->x = itemX->valueint;
                                gemdata->y = itemY->valueint;
                                gemdata->type = SIMPLE;
                                gemdata->collide_with_player = true;
                                arrayAdd(pss->simple_gems, gemdata);

                            }
                            cJSON *bomb_gems = cJSON_GetObjectItem(root, "bomb_gems");
                            for (int i = 0; i < cJSON_GetArraySize(bomb_gems); i++)
                            {
                                struct gem_data *gemdata = malloc(sizeof * gemdata);
                                cJSON * itemX = cJSON_GetArrayItem(bomb_gems, i);
                                ++i;
                                cJSON * itemY = cJSON_GetArrayItem(bomb_gems, i);
                                gemdata->x = itemX->valueint;
                                gemdata->y = itemY->valueint;
                                gemdata->type = BOMB;
                                gemdata->collide_with_player = true;
                                arrayAdd(pss->bomb_gems, gemdata);
                            }
                             
                            pss->score = score;
                            pss->collision_utc_timestemp = (long long)cJSON_GetObjectItem(root, "utc_timestemp")->valuedouble; //for tracking
                            lwsl_notice("INSIDE 2 pss->request_from_client_buf Movment : %s \n", pss->request_from_client_buf);
                            LOG_PRINT("INSIDE 2 pss->request_from_client_buf Movmente : %s \n", pss->request_from_client_buf);
                        }
                        lwsl_notice("END pss->request_from_client_buf Movment : %s \n", pss->request_from_client_buf);
                        LOG_PRINT("END pss->request_from_client_buf Movmente : %s \n", pss->request_from_client_buf);


      //pss->stop_player = stop_player;
      pss->done_srv_update = true;
      
                        struct per_session_data__apigataway *pssTmp  = hashmapPut(users_map_main, pss->player_id, pss);
                        if(pssTmp->collision_status == 8)
                        {
                            lwsl_notice("INSIDE HASHMAPPUT  pssTmp->request_from_client_buf Movment : %s \n", pssTmp->request_from_client_buf);
                            LOG_PRINT("INSIDE HASHMAPPUT  pssTmp->request_from_client_buf Movmente : %s \n", pssTmp->request_from_client_buf);
                        }
      break;
     }
     
     default:
      lwsl_notice("Invalid status \n");
       
    }    
   break;
  }
  case LWS_CALLBACK_RECEIVE:
  {
   if (len < 1)
   {
    break;
   }
   //lwsl_notice("Request from server: %s \n", (const char *)in);  
   pss->binary = lws_frame_is_binary(wsi);
    //memcpy(&pss->request_from_client_buf[LWS_PRE], in, len); 
   memcpy(&pss->request_from_client_buf, in, len);
   //lwsl_notice("pss->request_from_client_buf: %s \n", pss->request_from_client_buf);
   pss->recive_all_from_client = 1;
   //Only invoke callback back to client when baby client is ready to eat 
   lws_callback_on_writable(wsi);
   break;
  }
   /*
   * this just demonstrates how to use the protocol filter. If you won't
   * study and reject connections based on header content, you don't need
   * to handle this callback
   */
  case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
   //dump_handshake_info(wsi);
   /* you could return non-zero here and kill the connection */
   break;

   /*
   * this just demonstrates how to handle
   * LWS_CALLBACK_WS_PEER_INITIATED_CLOSE and extract the peer's close
   * code and auxiliary data.  You can just not handle it if you don't
   * have a use for this.
   */
  case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE:
  {
   lwsl_notice("LWS_CALLBACK_WS_PEER_INITIATED_CLOSE: len %d\n", len);
   for (n = 0; n < (int)len; n++)
   {
    lwsl_notice(" %d: 0x%02X\n", n, ((unsigned char *)in)[n]);
   }
 
   //update it to 6 which is this user is capot 
   pss->status =6;
   //we will use the registrator json , as only the status and the id is all it matters     
   int user_hash_size = hashmapSize(users_map_main);
   //lwsl_notice("response_to_client_cp : user_hash_size: %d \n", user_hash_size);
   if (user_hash_size > 1)
   {
    struct session_holder_data *session_holder_data_tmp = set_session_holder_data(user_is_dead_cp, pss);
    //now we have the others users which we need to update the current user 
    //preper the other players session structures 
    int i = 0;
    int size = arraySize(session_holder_data_tmp->players_session_holder);
    if (size > 0)
    {      
     while (i < size)
     {
      struct per_session_data__apigataway *other_p_session = arrayGet(session_holder_data_tmp->players_session_holder, i);
      //send current player to other players 
      int status = cJSON_GetObjectItem(pss->user_json_respose, "status")->valueint;
      //BUG in cJSON need to update also valuedouble when updating valueint
      //https://sourceforge.net/p/cjson/discussion/998969/thread/813ba29b/
      cJSON_GetObjectItem(pss->user_json_respose, "status")->valueint = 6;
      cJSON_GetObjectItem(pss->user_json_respose, "status")->valuedouble = 6;
     
      send_response(pss->user_json_respose, other_p_session, pss);
      // Move to next.
      i++;
      
     }
     arrayFree(session_holder_data_tmp->players_session_holder);
     free(session_holder_data_tmp);
    }
   }
   //send to self 
   char* resp_json = cJSON_Print(pss->user_json_respose);
   int n = sprintf((char *)p_response_to_clientout, "%s", resp_json);
   //lwsl_notice("Response to client from server: %s \n", p_response_to_clientout);
   //LOG_PRINT("Response to client from server: %s \n", p_response_to_clientout);
   //each player has its own copy of libwebsockets (lws in short ) wsi , witch is the player channel + session pointer 
   int m = lws_write(pss->player_wsi, p_response_to_clientout, n, LWS_WRITE_BINARY);
   if (m < n) {
    lwsl_err("ERROR %d writing to di socket\n", sizeof(response_to_client));
    LOG_PRINT("ERROR %d writing to di socket\n", sizeof(response_to_client));

   }
   //handle user that disconnected    
   //remove from users hash
   hashmapRemove(users_map_main, pss->player_id);
   int hash_map_size = hashmapSize(users_map_main);
   lwsl_notice("User %s disconnected: %s hashmap:%d \n", pss->player_name, pss->player_id, hash_map_size);
   LOG_PRINT("User %s disconnected: %s hashmap:%d \n", pss->player_name, pss->player_id, hash_map_size);

   //no players on the server reset gems 
   if (hash_map_size == 0)
   {
    if (gems_array != NULL)
    {
     int array_size = arraySize(gems_array);
     int i = 0;
     while (i < array_size) {
      lwsl_notice("clear count gem element ii:%d \n", i);
      struct gem_data* gd = arrayRemove(gems_array, i);
      int array_size1 = arraySize(gems_array);
      lwsl_notice("clear gem element ii:%d x:%d y:%d type:%d \n", i, gd->x, gd->y,gd->type);
      free(gd);
      array_size--;
     }
     //build again the gems 
     scatter_gems();
    }    
   }

   break;

   }
 
  default:
   break;
 }

 return 0;
}


I will explain the important Sections of the code , not in descending order,
But in the order of execution

Line 331: This is the main function we defined in the previous PART 2 .
This is the entry point in which all request will be captured .
Line 336 : init the hashmap which will hold all of our connections ( clients )
Lines 339 - 341 : init the session data structure , the one we defined in PART 2
in the protocols array

The big switch of web sockets connection States ,
each connection has state on his life cycle on each state callback will fire ,
this big switch will handle those callback by name

Lines 346 - 354:  LWS_CALLBACK_PROTOCOL_INIT 
This state will be called only ONCE  per session Usually good place to init stuff .we init here the Game Loop timer 

Lines 356 - 366: LWS_CALLBACK_ESTABLISHED
This state called when client connected to the server for the first time , called once per connection We allocate the session data structure and the basic parameters.
Lines 368 -  384: 
LWS_CALLBACK_SERVER_WRITEABLE: 
This callback will write back to the client , ONLY when the client ready to receive the response .
Lines 375 - 392: when client request registration , which means client hold the 0 state .
collect all data from the client request which arrived as JSON  format in to the session data structure.
Lines 393 - 422: when client request is movement , ( client is moving ) . 
which means client hold the 2 state . collect all data from the client request which arrived as JSON  format in to the session data structure.
Lines 425 - 483: collision detection code which is not implemented fully . so you can ignore it.
Lines 486 - 500: 
LWS_CALLBACK_RECEIVE:
Client request frames that are receiving . can be called several times per request .
Line 493: mark as binary request type
Line 499: libwebsockets API that command the server to send replay only when the client is ready to receive it .
Lines 518 - 600: 
LWS_CALLBACK_WS_PEER_INITIATED_CLOSE
When client connection is close for example when browser tab in which the game running is closed
When network is stop working , when game is closed and so on .
This callback will trigger , init we will clean the client connection from the main hashmap that holding the connections and do some memory cleaning . 

And inform OTHER PLAYERS that this current player has disconnected from the game .
Lines 527 - 558 : set this current player state to 6 which means this player is dead.
Lines 531 - 557 : send response to other players and inform them about the dead player.

Line 573: remove current player from the users hashmap 

The event driven programming is usually involve event that is fired on every event occurred .

And in this server is there is no exception , we using callback functions . allot .

Lines 147 - 284 : 
response_to_client_cp 
This callback function will be called each game loop tick every time there is a need to response to clients . It will response to clients based on states the client handled is in .
Lines 162 - 220: build response on registration state , inform others about new user joined to the game Lines 221 -277:
response to build response on movement state , inform others about new user joined to the game Lines 281:response to current connection ( current player ) .
Lines 314 -229: game_loop_cb
The game loop which will fire every 100ms , this will simulate the client game loop
And check the game logic , and response according to game events back to the clients 




Continue to PART 4 
where we examine the client side














Part 2: Multiplayer WebSocket Game server written in C using libuv & libwebsockets & Cocos2d-x-HTML5

Assuming the compilation of the server went as expected and the exe file did created.
You can start it clicking F5 in Visual Studio , the server will be listening for incoming requests
On port 7681.

Few Notes About the Client Server Architecture i use it this tutorial .
As mentioned in PART 1 of this tutorial , the example here going to implement the Authoritative server ,
In short what it means is the server will not send on each client game loop verification instead of it will send to the client the game status as played in the server , and the client will current the moves according to the server status or just keep with the game flow if its vaild . the client will use something called : client prediction , what this means in short is that the client will send to the server the game info that happens , but it will not wait for the verification for each step , it will just verify that the steps before the current step are done right . ( meter of milliseconds ) .

The source code :
ws_cococs_server_main.c 
This file will initialize the libuv framework and the libwebsockets
The libwebsockets will use the libuv event loop and other services and will take command on the entire server .




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "game_handler.h"
#include <uv.h>

int debug_level = 7;
struct lws_context *context;
#define MAX_ECHO_PAYLOAD 1024
static uv_timer_t timer_handle;
static int timer_cb_called;
static uv_once_t once = UV_ONCE_INIT;
static int once_cb_called = 0;
static int repeat_close_cb_called = 0;
static int once_close_cb_called = 0;
static int repeat_cb_called = 0;
static struct lws_protocols protocols[] = {  
 {
  "wsapi",
  callback_wsapi,
  sizeof(struct per_session_data__apigataway),
  MAX_ECHO_PAYLOAD,
 },
  
 { NULL, NULL, 0, 0 } /* terminator */
};
void signal_cb(uv_signal_t *watcher, int signum)
{
 lwsl_err("Signal %d caught, exiting...\n", watcher->signum);
 switch (watcher->signum) {
 case SIGTERM:
 case SIGINT:
  break;
 default:
  signal(SIGABRT, SIG_DFL);
  abort();
  break;
 }
 lws_libuv_stop(context);
}

int main(int argc, char **argv)
{
 struct lws_context_creation_info info;
 const char *iface = NULL;
 int opts = 0;
  uv_loop_t* loop = NULL;
 /* tell the library what debug level to emit and to send it to syslog */
 lws_set_log_level(debug_level, lwsl_emit_syslog);
 lwsl_notice("About to start server\n");

    memset(&info, 0, sizeof info);
 info.port = 7681;
 info.iface = NULL;
 info.protocols = protocols;
 info.extensions = NULL;
 info.ssl_cert_filepath = NULL;
 info.ssl_private_key_filepath = NULL;
 info.gid = -1;
 info.uid = -1;
 info.max_http_header_pool = 1;
 info.timeout_secs = 5;
 info.options = opts | LWS_SERVER_OPTION_LIBUV;

 context = lws_create_context(&info);
 if (context == NULL) {
  lwsl_err("libwebsocket init failed\n");
  return -1;
 }

 lws_uv_sigint_cfg(context, 1, signal_cb);
 if (lws_uv_initloop(context,NULL /*loop*/, 0)) {
  lwsl_err("lws_uv_initloop failed\n");

  goto bail;
 }

 lwsl_notice("server started\n");
 lws_libuv_run(context, 0);

bail:
 lws_context_destroy(context);
 lwsl_notice("server exited cleanly\n");


 return 0;
}

Lines 14 - 23:  libwebsockets part of it configuration we can define several protocols
Line 16: this is the uri which the client will call the web sockets request.
Line 17:callback_wsapi is the name of the main function which receive the client request.
Line 18:the size of the data structure which will hold the session data 
which means that each protocol can capture our request and process it
we are going to use only 1 protocol which process our web sockets requests
the HTTP hand shack authentication will be handled automatically by libwebsockets .
Lines 24 -35: callback which be called in case of context initialization failure . (line 68)
Lines 39 -84: configuration of libwebsockets
Line 50: server port
Line 60: configure libwebsockets to use libuv as its networking layer .

Continue to PART 3 server code
















Wednesday, August 10, 2016

Part 1: Multiplayer WebSocket Game server written in C using libuv & libwebsockets & Cocos2d-x-HTML5

The motivation to write this 6 part set of tutorials is to show developers how to build fast websockets game server Written in C using open source frameworks . and Cocos2d-x the HTML5 version for the  game client.

This tutorial is only to get your feet wet in this huge field of real time game servers .
It is real simple and teach you how to make single action , that is
moving players on all clients in real time .
also there are parts which are not finished yet like GEM"S on screen , ignore them for now.



This is the end result :



You can check the source code here :
https://github.com/meiry/Tutorial_mmo_websocket_game_server_c_libuv_libwebsockets_Cocos2d-x-HTML5

I'm quite aware of the huge hype using servers like Node.js for such tasks.or even Java Netty 
Especially when choosing event based a sync single thread server .
Although they are great servers and they are proven to be robust they have bottlenecks. for example:
(Notice those are very high level claims based on my own almost 20 years of development experience ).

Node.js using V8 engine as its JavaScript interpreter which originally designed for the chrome browser. huge frameworks are written in pure JavaScript which this browser interpreter needs to chew.

Java Netty is using the java JVM which it is a Software that execute your java Software in memory or not still.The JVM do take extra server resources despite the JVM have its own fine tuning configurations the results on very high load are sometimes unexpected . and of course the GC.

Therefore I want to present option which is not so popular BUT it will  probably utilize your physical server the most. and as result will save you money. 
see games like Agar.io or slither.io their server build using c++ .

The tutorials are written to show you the basic usage of client/server connectivity , don't expect to see full blown game made . this is just a demo .
I will use the Authoritative server model and Client side prediction , to read more about it please
Please Refer to this great theoretical explanation about this model:
http://www.gabrielgambetta.com/fpm1.html
Written by Gabriel Gambetta .

The server and client is build on top and with the help of those great open source cross platform libraries:
  1. Libuv  v1.90: this is the Node.js network library which abstracts the network event based model.
  2. libwebsockets  v2.0: cross platform C web sockets library
  3. list, hashmap , array files from android-system-core : C helpers  
  4. cJSON : fast c json writer/reader
  5. Cocos2d-x HTML5 : game engine. 

The project is developed in windows using Visual Studio  2013 c++  for the server.
And Chrome browser for the client .
Latter on i will add Linux and Mac support all code is cross platform .

Lets start with downloading libuv and libwebsockets and configuring them for compilation then compiling the server frameworks , after that we will learn the game server logic. and build simple client.

1. Libuv compilation.
Download libuv from the link below or git clone the master repository from here :
https://github.com/libuv/libuv
Then open the VS2013 x86 Native Tools Command Prompt  which located in the visual studio 2013
Tools directory .
browse to the libuv root directory and execute the vcbuild.bat :




After its done , it will create the VS Sulotion file in the root dir , open VS and load uv.sln
Then befor compiling go to Libuv -> right click -> properties -> C/C++ -> Code Generation
And chnage it to /MDd



Compile !
It create the libuv.lib file located in :
libuv\libuv-1.x\libuv-1.x\Debug\lib\libuv.lib
2. Libwebsockets compilation.
Download libwebsockets from the link below or git clone the master repository from here :
https://github.com/warmcat/libwebsockets

To configure and create the VS Solution files we will use CMAKE GUI tools , im using v3.5
Open cmake gui and point to the libwebsockets root directory .
And to the build directory where cmake will create the VS build files.
Click the configure button to revile the Cmake variables we need to feel .
It will open popup window there chose Visual Studio 2013



After the first configuration interation it will popup error window this is becose there few things we need to configure so libwebsockets work with libuv.
In the main cmake gui where its all painted in red do as follow : set the proper values

LWS_WITH_LIBUV    checked
LWS_WITH_STATIC   checked
LWS_WITH_SSL         un checked
LWS_LIB_INCLUDE_DIRS = d:\dev\cpp\gamedevcraft\libuv\libuv-1.x\libuv-1.x\include
LWS_LIBUV_LIBRARIES   = d:\dev\cpp\gamedevcraft\libuv\libuv-1.x\libuv-1.x\Debug\lib\libuv.lib

Click again configure , you should see the massage : Configuration Done .




Click the Generate button , the massage : Generate done  should appear .



Now go to the build directory and load the libwebsockets.sln solution file into VS 2013.
We only need to compile websockets project . so compile it .
The product will be static libwebsokctes file : websockets_static.lib this is the file we are going to use together with libuv compiled statically to our main server application .

3.Creating the VS project for our server.

First Download the source code of the game server from this GitHub repository :
https://github.com/meiry/Tutorial_mmo_websocket_game_server_c_libuv_libwebsockets_Cocos2d-x-HTML5
These files are the logic of the game server .
In VS go to :
Open -> New Project ->Visual C++ -> Win32 Console Application ,
At the button in the same window give the project name :

I called it "libuv_libwebsocket_cocos2dx_server" , and set directory for the project.
Then press Ok .
In the Next window click the the Next button
In the third window Uncheck the "Precompiled header" and click "Finish".
Now that you created the project lets import the source files and configure the project .
Copy the files which downloaded from GitHub and copy them to the root of the new created project.
Create new directory called libs  also in the root directory
Into the libs directory copy the libraries we compiled in the previous steps (1 & 2) :
libuv.lib , websockets_static.lib , zlib_internal.lib

sources :

libs:



We now going to add all those libs + headers + sources files into our VS project .
Right click on the "Header Files" in the new created project in VS  go to :
Add -> Existing item
Browse to the new created project root directory  and select all the headers there



Do the same but now right click on the source directory in VS under the new project and add the C files :



You need also include the cJSON c file , so repeat the same process for the files: cJSON_Utils.c cJSON.c


Project configuration :
Right click on the project go to :

C/C++ -> General -> Additional include Directories :  add the headers path
include;include\uv;include\lws;include\lws\win32helpers\;include\cjson;





Then go to:
C/C++ ->  Preprocessor -> Preprocessor definitions

Verify you have those set :
WIN32
_DEBUG
_WINDOWS
_CONSOLE
_LIB
_CRT_SECURE_NO_DEPRECATE
_CRT_NONSTDC_NO_DEPRECATE

Then go to:
C/C++ -> Code generation -> Runtime library 


And verify it set to (/MDd) 


Then go to :
Linker -> General -> Additional Library Directories And add the libs directory we created in the previous step




Then go to :
Linker -> Input -> additional dependencies
And verify you have those library names ( this part will be different in Linux configuration )

advapi32.lib
iphlpapi.lib
psapi.lib
userenv.lib
ws2_32.lib
libuv.lib
websockets_static.lib
zlib_internal.lib



Then go to :
Linker ->SubSystem 
verify it set to  : Console (/SUBSYSTEM:CONSOLE)

That's all ! compile the project
You should see  build\Debug\libuv_libwebsocket_cocos2dx_server.exe  file create.

Go to PART 2 where we dive into the server source code