Friday, August 12, 2016

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

This class is where all the game logic happens .
If you remember i I mentioned before about client prediction method , which makes the game to look
As it runs smooth without getting verification on each move . only authentication about the moves.
And if its wrong it will correct the position .

GameLayer.js
  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
var spriteFrameCache = cc.spriteFrameCache;
var spriteFrameCacheGems = cc.spriteFrameCache;
var TAG_PLAYER_NODE = 2;
var TAG_GEM_NODE = 1;
var TAG_BOMBOMB_NODE = 1;
var ZORDER_PLAYER_NODE = 4;
var ZORDER_GEM_NODE = 1;
var player = null;
var players ={};
var gems = [] ;
var endPlayerPos = null;
var distance  = null;
var directionX = null;
var directionY = null;
var startY = null;
var startX = null;
var speed = 300; 
var distance = null;
var m_websocketMng = null;
var counter_from_server_tmp =0;
var gemBomb = null;
var scoreLabel = null;

var GameLayer = cc.LayerColor.extend({
    sprite:null,
 winsize:null,
 player_seq:0,
 otherPlayersMoved:false,
  
    ctor:function (_websocketMng) {
    m_websocketMng = _websocketMng;
    this._super(cc.color(0, 128, 255, 255));
       this.winsize = cc.director.getVisibleSize(); //cc.winSize;
        
       var listener = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: function (touch, event) {
                 
                var touchLocation = touch.getLocation();
     
    if(player!=null)
    {
     //float can't maintain its value "as is" , so it will be saved as string 
     //http://stackoverflow.com/questions/588004/is-floating-point-math-broken
     endPlayerPos = touchLocation;
     player.setEndPosX(endPlayerPos.x);
     player.setEndPosY(endPlayerPos.y);
     distance  = Math.sqrt(Math.pow((endPlayerPos.x - player.x),2) + Math.pow((endPlayerPos.y - player.y),2) );
     directionX = (endPlayerPos.x - player.x) / distance;
     directionY = (endPlayerPos.y - player.y) / distance;
     if(isNaN(directionX) || isNaN(directionY) )
     {
      directionY = directionX = 0;
     }
     startY = player.y;
     startX = player.x;
     player.startAnim();
     player.setMoving(true);       

    }                    
                return true;
                
            },
            onTouchMoved: function (touch, event) {
                //this.setPosition(this.getPosition() + touch.getDelta());
            },
            onTouchEnded: function (touch, event) {
                
                
            }
       });
       cc.eventManager.addListener(listener, this);
       this.schedule(this.gameLoop); 
   
    },
        
    
 onEnter:function () {
  this._super();
  
  var visibleOrigin = cc.director.getVisibleOrigin(); 
  scoreLabel = new cc.LabelTTF("0", "Arial",80);
  var scoreLabelcontentSize = scoreLabel.getContentSize();
        this.addChild(scoreLabel,20);
        scoreLabel.setPosition(cc.p(visibleOrigin.x + scoreLabelcontentSize.width, visibleOrigin.y + winsize.height - scoreLabelcontentSize.height)); 


  var msgProtocolContainer = m_websocketMng.getMsgProtocol();
  spriteFrameCache.addSpriteFrames(res.char_anim_plist,res.char_anim_png);
  player = Player.initSpriteFrame(spriteFrameCache.getSpriteFrame(this.getImageByState(states.PLAYER_B)),
                  states.PLAYER_B,
                  msgProtocolContainer.msgProtocol.player_name,
                  msgProtocolContainer.msgProtocol.player_id); 
  player.setXY(this.winsize.width / 2,this.winsize.height / 2);    
  this.addChild(player,ZORDER_PLAYER_NODE,TAG_PLAYER_NODE);
  //check if players exists
  if(msgProtocolContainer.msgProtocol.hasOwnProperty("players"))
  {
   for (var i = 0; i < msgProtocolContainer.msgProtocol.players.length; i++) { 
        this.AddOtherPlayerOnRegister(msgProtocolContainer.msgProtocol.players[i]);
   }
  }
  //handle gems if they exists
  if(msgProtocolContainer.hasOwnProperty("msgProtocolGems"))
  {
   this.scatterGems(msgProtocolContainer.msgProtocolGems);
  }
  //set this object to websocketMng so it can delegate back to here function calls
  m_websocketMng.setObjByStatus(this,null,100);

 },
 scatterGems:function(_msgProtocolGems)
 {
  if(_msgProtocolGems.hasOwnProperty("simple_gems"))
  {
   for (var i = 0; i < _msgProtocolGems.simple_gems.length; i++) { 
        this.AddBasicGemsToGame(_msgProtocolGems.simple_gems[i],
               _msgProtocolGems.simple_gems[++i]);
        
   }
  }
  if(_msgProtocolGems.hasOwnProperty("bomb_gems"))
  {
   for (var i = 0; i < _msgProtocolGems.bomb_gems.length; i++) { 
        this.AddBombGemsToGame(_msgProtocolGems.bomb_gems[i],
              _msgProtocolGems.bomb_gems[++i]);
        
   }
  }
 },
 AddBasicGemsToGame:function(_basicGem_x,_basicGem_y)
 {
  var gem1Basic = Gem.initSprite(null,states_gems.SIMPLE);
  this.addChild(gem1Basic,ZORDER_GEM_NODE,TAG_GEM_NODE);
  gem1Basic.x = _basicGem_x;
  gem1Basic.y = _basicGem_y;   
  gems.push(gem1Basic);
  //cc.log("gem1:"+gem1.x+"  "+gem1.y); 
 },
 AddBombGemsToGame:function(_bombGem_x,_bombGem_y)
 {

  spriteFrameCacheGems.addSpriteFrames(res.gem_b_anim_plist,res.gem_b_anim_png);
  gemBomb = Gem.initSprite(spriteFrameCacheGems.getSpriteFrame(this.getImageByState(states.BOMB)),states_gems.BOMB); 
  this.addChild(gemBomb,ZORDER_PLAYER_NODE,TAG_BOMBOMB_NODE);
  gemBomb.x = _bombGem_x;
  gemBomb.y = _bombGem_y;
  gems.push(gemBomb);
  //cc.log("gemBomb:"+gemBomb.x+"  "+gemBomb.y);
 },
 AddOtherPlayerOnRegister:function(_ResponseFromServer) {
  var otherPlayer = Player.initSpriteFrame(spriteFrameCache.getSpriteFrame(this.getImageByState(states.PLAYER_B)),
                  states.PLAYER_B,
                  _ResponseFromServer.player_name,
                  _ResponseFromServer.player_id); 
  var x_ = parseFloat(_ResponseFromServer.end_player_pos_x);
  var y_ = parseFloat(_ResponseFromServer.end_player_pos_y);
  //otherPlayer.setXY(this.winsize.width / 2,this.winsize.height / 2); 
  otherPlayer.setXY(x_,y_); 
  var otherplayer_id = otherPlayer.getId();
  players[otherplayer_id.toString()] = otherPlayer;
  //cc.log(Object.keys(players).length);   
  this.addChild(otherPlayer,1,TAG_PLAYER_NODE);
    
 },
 deletePlayer:function(_ResponseFromServer)
 {
  var p = players[_ResponseFromServer.player_id.toString()];
  this.removeChild(p);
  delete players[_ResponseFromServer.player_id.toString()];
 },
 updateOtherPlayerOnMovment:function(_ResponseFromServer)
 { 
 
  var p = players[_ResponseFromServer.player_id.toString()];
  players[_ResponseFromServer.player_id.toString()].pushToResponsesList(_ResponseFromServer); 
  if(players[_ResponseFromServer.player_id.toString()].player_x_r.length == 0 && players[_ResponseFromServer.player_id.toString()].getAnimStatus() == false)
  {
   players[_ResponseFromServer.player_id.toString()].startAnim();
  }
  players[_ResponseFromServer.player_id.toString()].player_x_r = players[_ResponseFromServer.player_id.toString()].player_x_r.concat(_ResponseFromServer.player_x_r);
  players[_ResponseFromServer.player_id.toString()].player_y_r = players[_ResponseFromServer.player_id.toString()].player_y_r.concat(_ResponseFromServer.player_y_r);
  if(parseInt(_ResponseFromServer.collision_status) == 9)
  {
   players[_ResponseFromServer.player_id.toString()].simple_gems = _ResponseFromServer.simple_gems;
   players[_ResponseFromServer.player_id.toString()].bomb_gems = _ResponseFromServer.bomb_gems;
   players[_ResponseFromServer.player_id.toString()].status = _ResponseFromServer.status;
   players[_ResponseFromServer.player_id.toString()].player_id = _ResponseFromServer.player_id;
   players[_ResponseFromServer.player_id.toString()].utc_timestemp = _ResponseFromServer.utc_timestemp;
   players[_ResponseFromServer.player_id.toString()].score = _ResponseFromServer.score;
   players[_ResponseFromServer.player_id.toString()].collision_status  = _ResponseFromServer.collision_status;
   console.log("players["+_ResponseFromServer.player_id.toString()+"].collision_status:"+players[_ResponseFromServer.player_id.toString()].collision_status);
  }
  counter_from_server_tmp++;
 },
 updateScoreAndGems:function(_player)
 {
  var simple_gems = _player.simple_gems;
  var bomb_gems = _player.bomb_gems;
   
  
  for(var i =0 ; simple_gems.length;i++)
  {
   this.searchAndRemoveSimpleGems(simple_gems[i],simple_gems[++i]);
  }
  
 },
 searchAndRemoveSimpleGems:function(_simple_gems_x,_simple_gems_y)
 {
  for(var i=0;i<gems.length;i++)
  {
    
   var xx = gems[i].x;
            var yy = gems[i].y;
            
          if(_simple_gems_x == xx && _simple_gems_y == yy)
          {
           //remove from game layer 
          this.removeChild(gems[i]);
          //remove from gems array repo
    gems.splice(i, 1);
    break;
          }
     
  }

 },
 gameLoop:function (delta) {
  //http://gamedev.stackexchange.com/questions/23447/moving-from-ax-y-to-bx1-y1-with-constant-speed
  //handle other players movment 
  if(Object.keys(players).length>0 )
  {
   for(var i=0;i<Object.keys(players).length;i++)
   { 
    
    var playerKey = Object.keys(players)[i].toString();
    if(players[playerKey].getResponsesList()==null)
    {
     continue;
    }
    //cc.log("playerKey:"+players[playerKey].player_name+" "+players[playerKey].serverResponsesList.length+" "+players[playerKey].player_id);     
    if(players[playerKey].getResponsesList().length == 0)
    {
     continue;
    }
    //get the first response from server 
    var stopAnim = 0;
    var playersResponsesListLen  = players[playerKey].getResponsesList().length;
     
    if(players[playerKey].player_x_r.length > 0)
    {
     var x_ = parseFloat(players[playerKey].player_x_r.shift());
     var y_ = parseFloat(players[playerKey].player_y_r.shift());
     //console.log("FROM GAMELOOP:"+players[playerKey].player_name+" x:"+x_);
     //console.log("FROM GAMELOOP:"+players[playerKey].player_name+" y:"+y_);
     console.log("players[playerKey].player_name:"+players[playerKey].player_name+"  players["+playerKey+"].collision_status:"+players[playerKey].collision_status);
     players[playerKey].move(x_,y_);
     if(players[playerKey].collision_status == 9)
     {
      //this.updateScoreAndGems(players[playerKey]);
       cc.log("players[playerKey].collision_status");
      //players[playerKey].collision_status = 0;
     }
    }
    
   }
  }

  if(player.getMoving() == true)
  {
   var x = directionX * speed * delta;
   var y = directionY * speed * delta;
   //console.log("PLAYER:"+player.player_name+" x:"+x);
   //console.log("PLAYER:"+player.player_name+" y:"+y);
   player.move(x,y);
   var playerRect2 = player.getTheBoundingBox2(); 
   //cc.log("Player x:"+playerRect2.x+" y:"+playerRect2.y);
   //client adds a sequence number to each request
   //client send move state 
   var msgProtocolObj = new MsgProtocol();
   //IMportent as deleta time is part of the calculation of each client , we need to send  direction * speed
   //player_x and player_y will be used only for player prediction validation                         
   msgProtocolObj.player_x = x.toString();
   msgProtocolObj.player_y = y.toString();
   msgProtocolObj.player_seq = this.player_seq.toString();
   msgProtocolObj.status = 2;
   msgProtocolObj.collision_status =0;
   msgProtocolObj.player_id = player.getId();
   //keep track of the end move or the player 
   msgProtocolObj.end_player_pos_x=endPlayerPos.x.toString();
   msgProtocolObj.end_player_pos_y=endPlayerPos.y.toString();
   msgProtocolObj.stop_player
   //keep track of the player movement for client side prediction and Synchronization 
   //player.movmet_sequence_history.push(MsgProtocol);
   //As hashmap
   player.movmet_sequence_history[msgProtocolObj.player_seq] = msgProtocolObj;
   //send the  predicted movment to the server
   //m_websocketMng.sendMassage(msgProtocolObj,this);
   //this.player_seq++;

   //var isCollision = player.BorderCollisionDetection(this.winsize); 
   //Clollison 
    
            
            var playerRect2 = player.getTheBoundingBox2();  
             
            var gemsToDelMap = [] ;
            var xx ,yy = 0; 
   for(var i=0;i<gems.length;i++)
   {
    var gemRect = gems[i].getBoundingBox();      
    if ( cc.rectIntersectsRect(gemRect,playerRect2 ) )
    //if(cc.rectContainsPoint(playerRect2, cc.p(gemRect.x,gemRect.y)))
                {
                    cc.log("cc.intersectsRect(gemRect,playerRect2 )");
                     if(gems[i].state == states_gems.SIMPLE)
                     {
                       //inc the player score when it hit the gem
                       if(xx != gems[i].x && yy != gems[i].y)
                       {
                        xx = gems[i].x;
                        yy = gems[i].y;
                        //cc.log("inside rectIntersectsRect:xx:"+xx+"  yy:"+yy);
                        //cc.log("inside rectIntersectsRect"+gems[i].getPosition().x+"  "+gems[i].getPosition().y);
                        player.score++;
                        gemsToDelMap[i.toString()] = gems[i];
                        scoreLabel.setString(player.score); 
                        //remove from game layer 
                        this.removeChild(gems[i]);
                        //remove from gems array repo
        gems.splice(i, 1);
        //inc the for loop 
        i++;

                       }
                     }
                }   
   }
   if(Object.keys(gemsToDelMap).length>0)
   {
    this.handleGemCollided(gemsToDelMap,msgProtocolObj);
   }
   //handle game window border 
   if((Math.sqrt(Math.pow(player.x-startX,2)+Math.pow(player.y-startY,2)) >= distance) )
   {
    player.setMoving(false); 
    player.stopAnim();
    msgProtocolObj.stop_player = 1;
    //m_websocketMng.sendMassage(msgProtocolObj,this);
   } 
   m_websocketMng.sendMassage(msgProtocolObj,this);
   //console.log("PLAYER:"+msgProtocolObj+" y:"+y);
   this.player_seq++;

  }
    }, //End Game Loop
    //Handle the player and the gems collided and send to the server 
    handleGemCollided:function(_gemsToDelMap,_msgProtocolObj)
    {
     if(Object.keys(_gemsToDelMap).length>0 )
  {

   //var msgProtocolObj = new MsgProtocol();
   //IMportent as deleta time is part of the calculation of each client , we need to send  direction * speed
   //player_x and player_y will be used only for player prediction validation   
   _msgProtocolObj.player_name =player.player_name ;
   _msgProtocolObj.player_id= player.player_id;
   _msgProtocolObj.utc_timestemp= getUTCTimestamp();
   _msgProtocolObj.simple_gems = [];
   _msgProtocolObj.bomb_gems = [];
   _msgProtocolObj.score = player.score;  
   _msgProtocolObj.collision_status =8;
   //Extract the gems to send to the server , the keys are the positions the server set to the gems 
   for(var i=0;i<Object.keys(_gemsToDelMap).length;i++)
   { 
    var gemsToDelKey = Object.keys(_gemsToDelMap)[i].toString();
    var gemX = _gemsToDelMap[gemsToDelKey].x;
    var gemY = _gemsToDelMap[gemsToDelKey].y;
    if(_gemsToDelMap[gemsToDelKey].type == states_gems.SIMPLE)
    {
     _msgProtocolObj.simple_gems.push(gemX); 
     _msgProtocolObj.simple_gems.push(gemY); 
    }
    if(_gemsToDelMap[gemsToDelKey].type == states_gems.BOMB)
    {
     _msgProtocolObj.bomb_gems.push(gemX);
     _msgProtocolObj.bomb_gems.push(gemY);
    }
   }
    
   //var buf = Encode(msgProtocolObj);
         //cc.log("FROM CLIENT SCORE:"+buf);
   //m_websocketMng.sendMassage(msgProtocolObj,this);
  }
    },
    syncPlayerActions:function(_ResponseFromServer)
    {
     var fraud = true;
     var i =0;
     //handel the client prediction and the server response .
     //1. check the last seq element first if it is in the client history  

     var srv_player_seq_len = _ResponseFromServer.player_seq.length;
     var srv_player_seq_elm = _ResponseFromServer.player_seq[srv_player_seq_len-1];
     //create new copy of player so it not be affected from the main player instace which get updated in the game loop 
     var PlayerCopy = player;
     //cc.log("Create new PlayerCopy");
     //check if there is seq tag in the client history hash
     if(srv_player_seq_elm in PlayerCopy.movmet_sequence_history)
     {
      //get the msg_protocol from client by the seq name from server 
      var cln_msg_protocol = PlayerCopy.movmet_sequence_history[srv_player_seq_elm];
      //check if there is match 
      var srv_player_player_x_r_elm = _ResponseFromServer.player_x_r[srv_player_seq_len-1];
      var srv_player_player_y_r_elm = _ResponseFromServer.player_y_r[srv_player_seq_len-1];
      if(cln_msg_protocol.player_x == srv_player_player_x_r_elm && 
         cln_msg_protocol.player_y == srv_player_player_y_r_elm)
      {
       //If it got to this point this mean that the history from this point and back needs to be cleaned 
       fraud = false;
       PlayerCopy = null;
       //cc.log("Delete PlayerCopy");      
      }
     }
    },
 getImageByState:function(stateimg) {
  //cc.log("stateimg:"+stateimg);
  switch(stateimg)
  {   
   case states.PLAYER_B:
   {      
    return "l0_sprite_b_1.png";
   }
   case states.PLAYER_Y:
   {      
    return "l0_sprite_y_1.png";
   }
   case states.PLAYER_R:
   {      
    return "l0_sprite_r_1.png";
   }
   case states.BOMB:
   {      
    return "sprite_gem_b0.png";
   }
  }
 }
});

Lines 30 : The class constructor .
Lines 35-40: setting the touch listener , to support single touch each time.
Lines 42-61:we need to calculate the direction between the touch and the position of the player
For this when the user of the game touch the screen the position of the touch is saved and also distance and the the direction .
Lines 73-74:The initialization of the EventManger which takes the listener object that was defined.
then the game loop starts (the scheduler ) and calls the gameloop function.
Note that there is also game loop in the server . the real game logic will be happening in the server
Here the game loop will only be used to move the objects .
Lines 79 -96: When layer is created there are 2 phases.
1. Object initialization and this is when the constructor is called
and then
2. When layer is done rending this is when OnEnter called .
In this function we set the player in its first position .
Lines 100-102: Checking if there are also extra "Players" which we need to render.
This mean that when the player is created on the server , the server also will add to the player the additional player that are in the game .
Lines 152 - 164: AddOtherPlayerOnRegister this function will create new Player on the client game 
those player will be driven only by the data that is received from the server .
Lines 167-171:
deletePlayer this function will delete the player from the screen and also from the
player[] hash map
Lines 173-193: 
updateOtherPlayerOnMovment when response from there server arriving with value 4 
when this function is called few actions is taken 
1. the player get fatched from the player map by the player id 
2. check is preformed to see if the movement array (
player_x_r ,player_y_r ) contains data
3. start the player animation id does .
Lines 229 - 263: The main GameLoop this function is divided to 3 main parts. 
first is the part where it takes cars the "other players" which are the players connected to the server 
and we can see them in our client . on each tick of the game loop ( which means every time the gameloop function get called).
the loop will check if there are players that needs to be handled .
Lines 270-297:The second part of the gameloop . in this part the current player is handled
and the client prediction mechanism kicked in . in short what this mean is that the player
no matter what keeps moving where it is supposed to more .and the movements are kept in the :

movmet_sequence_history Array in lines 281 - 293 we are creating the protocol object that is
ready to be send to the server but JUST NOT NOW.
Lines 397-425: The Third part is where the client start to synchronize with the data that is  received from the server. the data will be always what is calculated ( in our case only the  player movements)
step before the present movement . this is the client side prediction verification.
if it out of sync it will correct it self on the client .


Thats it ! Start the server , run multiple browser clients and see them move .
I hope you had fun to learn some new stuff .
Please register my mailing list to get new updates


 



 




 

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

The Web Sockets Class is the class where the Requests / Responses are happening.
It using the native HTML5 Web Sockets interface / API .
All requests will process through this class and all response will process through this class also
All web-sockets validations / and function dispatching will also triggered from here .

Websockts.js
 
  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
var WebSocket = WebSocket || window.WebSocket || window.MozWebSocket; 

var MsgProtocolContainer =  function() 
{
 this.msgProtocol = new MsgProtocol();
 this.msgProtocolGems = new MsgProtocol();
}
var WebSocketNode = cc.Node.extend({
     m_wsiSendBinary:null,
     m_loginObj:null,
     m_GameLayer:null,
     m_msgProtocolContainer:null,
     ctor:function () {
         this._super(); 
         this.winsize = cc.winSize;
         this.m_msgProtocolContainer = new MsgProtocolContainer();        
     },
     init: function () {
        this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
        this.m_wsiSendBinary.binaryType = "arraybuffer";
        this.m_wsiSendBinary.onopen = function(evt) {
            cc.log("Send Binary WS was opened.");
        };

        this.m_wsiSendBinary.onmessage = (function(evt) {
      var binaryUint8 = new Uint8Array(evt.data);
      var binaryStr = '';
      for (var i = 0; i < binaryUint8.length; i++) {
           binaryStr += String.fromCharCode(binaryUint8[i]);
      }
            // cc.log(binaryStr);
             this.handleServerResponse(binaryStr);


         this.m_wsiSendBinary.onerror = function(evt) {
             //this.m_loginObj.serverofflineLabel = 180;
            cc.log("m_wsiSendBinary Error was fired");
             if (cc.sys.isObjectValid(self)) {
                //self._errorStatus.setString("an error was fired");
                cc.log("an error was fired");
            } else {
                cc.log("WebSocket test layer was destroyed!");
            }
        };

        this.m_wsiSendBinary.onclose = function(evt) {
            cc.log("m_wsiSendBinary websocket instance closed.");
            self.m_wsiSendBinary = null;
        };
            
        }).bind(this);

       
         return true;
     },
     getMsgProtocol:function()
     {
      return this.m_msgProtocolContainer;
     },
     handleServerResponse:function(binaryStr)
     {
    var ResponseFromServer = Decode(binaryStr);
     
    //cc.log(Encode(ResponseFromServer));
     switch(ResponseFromServer.status)
     {
      case 1:
      {
       //cc.log(ResponseFromServer.player_id);
       this.m_msgProtocolContainer.msgProtocol.player_id = ResponseFromServer.player_id;
       if(ResponseFromServer.hasOwnProperty("players"))
       {
        this.m_msgProtocolContainer.msgProtocol.players = ResponseFromServer.players;
       }
       this.m_loginObj.switchToGame();
       break;
      }
      case 3:
      {
       this.m_GameLayer.syncPlayerActions(ResponseFromServer);
       break;
      }
      case 4:
      {
       this.m_GameLayer.AddOtherPlayerOnRegister(ResponseFromServer);
       break;
      } 
      case 5:
      {
       this.m_GameLayer.updateOtherPlayerOnMovment(ResponseFromServer);
       break;
      } 
      case 6:
      {
       this.m_GameLayer.deletePlayer(ResponseFromServer);
       break;
      } 
      case 7:
      {
       this.m_msgProtocolContainer.msgProtocolGems.simple_gems = ResponseFromServer.simple_gems;
       this.m_msgProtocolContainer.msgProtocolGems.bomb_gems = ResponseFromServer.bomb_gems;
       this.m_msgProtocolContainer.msgProtocolGems.status = ResponseFromServer.status;
       this.m_msgProtocolContainer.msgProtocolGems.player_id = ResponseFromServer.player_id;
       this.m_msgProtocolContainer.msgProtocolGems.utc_timestemp = ResponseFromServer.utc_timestemp;
       break;
      }       
     }
     
     },
     _stringConvertToArray:function (strData) {
         if (!strData)
         {
             return null;
         }

         var arrData = new Uint16Array(strData.length);
         for (var i = 0; i < strData.length; i++) {
             arrData[i] = strData.charCodeAt(i);
         }
         return arrData;
     },
     _stringConvertToUint8Array:function (strData) {
       
      // View the byte buffer as an array of 8-bit unsigned integers
      var arrData = new Uint8Array(strData.length);
      for (var i=0;i<strData.length;++i) {
          arrData[i] = strData.charCodeAt(i);
      }
      // Log the binary array
      //cc.log("SEND ARRAY BUFFER: " + arrData.buffer);
      return arrData;
     },

     sendMassage: function(reqJson,_obj)
     {
      this.setObjByStatus(_obj,reqJson,reqJson.status);

         if (this.m_wsiSendBinary.readyState == WebSocket.OPEN)
         {
            // cc.log("Send Binary WS is waiting...");
             var buf = Encode(reqJson);
             //cc.log("FROM CLIENT:"+buf);
             //console.log("PLAYER SEND:"+reqJson.player_name+" x:"+reqJson.player_x);
    //cc.log("PLAYER SEND X:"+reqJson.player_name+" x:"+reqJson.player_x);
    //cc.log("PLAYER SEND Y:"+reqJson.player_name+" y:"+reqJson.player_y);
             var binary = this._stringConvertToUint8Array(buf);
             if(reqJson.status==2)
       {
        var buf1 = Encode(reqJson);
            cc.log("FROM CLIENT reqJson.status==2:"+buf1);
       }
       else if(reqJson.status==8)
       {
      var buf1 = Encode(reqJson);
            cc.log("FROM CLIENT reqJson.status==8:"+buf1);
       }
             this.m_wsiSendBinary.send(binary.buffer);
         }
         else
         {
             var warningStr = "send binary websocket instance wasn't ready...try again in few seconds";
             cc.log(warningStr);
             this.init();
            
              
         }
     },
     setObjByStatus: function(_obj,_reqJson,_status)
     {
      switch(_status)
      {
       case 0 :
       {
        this.m_msgProtocolContainer.msgProtocol.player_name = _reqJson.player_name;
        
     this.m_msgProtocolContainer.msgProtocol.end_player_pos_x=this.winsize.width / 2;
     this.m_msgProtocolContainer.msgProtocol.end_player_pos_y=this.winsize.height / 2;
        this.m_loginObj = _obj;
        break;
       }
       case 2 :
       {
        this.m_msgProtocolContainer.msgProtocol.player_x = _reqJson.player_x;
        this.m_msgProtocolContainer.msgProtocol.player_y = _reqJson.player_y;
        this.m_msgProtocolContainer.msgProtocol.player_seq = _reqJson.player_seq;
        this.m_msgProtocolContainer.msgProtocol.status = _reqJson.status;
        this.m_GameLayer = _obj;
        break;
       }
       case 100 :
       {
        this.m_GameLayer = _obj;
        break;
       }

      }
     }

});

Lines 1 : this is Cocos2d-x declaration to support cross device web sockets
on the web it is naive HTML5 , in desktop and mobile it is libwebsockets , which we are using in the server also .
Lines 18 -23: Initialize the WebSocket HTML 5 object with the Server ip and port in the constructor
Notice we using the wsapi uri as in our server protocol API name < MEIRY todo link >
We set the massaging type to be binary type for speed .
Also setting the WebSocket onopen listener which is triggered when the connection is successful .
Lines 25 -32: When massage Arived from the server it is coming as binary format , which we need to parse back to text format ,
Then the text massage will be send to handleServerResponse function which is well .. handle the responses (:
Lines 60 - 109: This is the response handler function which based on the game protocol state received
The action is chosen . the function are invoked in the Gamelayer object .
Lines 134 - 167: this function will send the request to the server but before that it will convert the text massage to binary type .  line 146 . and if there are modifications to be done based on the protocol state this is the place they will happen .  lines 157 and 147.



Continue to PART 6 client code where we examine GameLayer.js















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

In this set of tutorials i will show you how to create the client side AKA the game .
Please dont expect to see "real" game . its just demo which demonstrate
I will use Cocos2d-x the HTML5 version which means you can take the code and compile it
To iOS and desktop and android see previous tutorial 
  1. Players registration
  2. Players movements
  3. All clients get updates from the server about other players 
  4. gem and bombs and collisions detection not implemented yet , but there is initial code there
    please ignore it for now.
After done creating the project copy the game files and overwrite the default files.
To run the game client in the browser we need to download some HTTP server.
it can be : Apache / tomcat / nginx what ever , i use this personal web server called Mongoose 
which is used in embed devices like cars .....
(yeah ... look in the "about" in the multimedia console in your car ).

I will not explain the very simple files which are just class's which hold data to be used in game .
Player.js: Player class representation.
Protocol.js : misc data structures and simple functions that are used in the game.
other files you can ignore

Lets dive in with the main files :
LayerController.js



 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
var websocketMng = null;
var LayerController = cc.Layer.extend({
 winsize:null,
    ctor:function () {
    this._super();
       this.winsize = cc.winSize;     
       return true;
    },
 onEnter:function () {
  this._super();
  websocketMng = new WebSocketNode(); 
   websocketMng.init();
  var logInlayer = new LogInlayer(websocketMng);
        var gameLayer = new GameLayer(websocketMng);
        var layer = new cc.LayerMultiplex(logInlayer,gameLayer);
        this.addChild(layer, 0);
 }
});

var LayerControllerScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layerController = new LayerController();
        this.addChild(layerController);
    }
});

Lines 2- 17 :  load the game first layer initialize the game objects
the websockets/LogInLayer/GameLayer class's
The base layer will be of type  "LayerMultiplex" in cocos2d-x it means it will load 2 scenes and switch between them .
The first Layer that will be load is The LogInlayer.

Lines 20 - 25: load the main Scene and add the layer controller as child.


Login.js
This class is the login module , the first screen which the player see when loging to the game
The player set its name , press "LogIn" button ,
Few things are happening behind the stage.

  1. The Connection to the WebSockets server is established 
  2. The Server creates the player session 
  3. The Player instance is created in the client 
  4. The next Layer is switched , this is the main game layer.



 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
 
 var loginSprite = null;
 var m_websocketMng = null;
 var winsize = null;

 var LogInlayer = cc.Layer.extend({
    
    ctor:function (_websocketMng) {
       this._super();
       m_websocketMng = _websocketMng;
       winsize = cc.winSize;       
       return true;
    },
    onEnter:function () {
        this._super();
        loginSprite = Login.initSprite();
        loginSprite.x = winsize.width / 2;
        loginSprite.y = winsize.height / 2;
        this.addChild(loginSprite, 0);
    }
});

var Login = cc.Sprite.extend({
    Editbox:null,
    EditBoxText:null,
    serverofflineLabel:0,
 ctor: function(){
        this._super();

        
    },
 onEnter:function () {
  this._super();
  this.initWithTexture(cc.textureCache.addImage(res.blank_png));
        this.setTextureRect(cc.rect(0,0,500,400));
        this.setAnchorPoint(0.5, 0.5);
        this.setColor(cc.color(0, 50,111,50)); 
        this.setXY(cc.winSize.width/2,cc.winSize.height/2);
          // Create the textfield
       this.Editbox = new cc.EditBox(cc.size(180,50), new cc.Scale9Sprite(res.yellow_edit_png));
       this.Editbox.setFont("Ariel",25);
        this.Editbox.setPlaceholderFontColor(cc.color(255, 0, 0));
        this.Editbox.setPlaceHolder("Enter Name:");
        this.Editbox.x = this.getContentSize().width/2;
        this.Editbox.y = this.getContentSize().height/2;
        this.Editbox.setDelegate(this);
        this.Editbox.setFontColor(cc.color(5, 4, 10));
        this.Editbox.setMaxLength(20);

        var LogIn_item = new cc.MenuItemFont("LogIn", this.onMenuLogInCallback,this);
        var menu = new cc.Menu(LogIn_item);
        menu.x = this.getContentSize().width/2;
        menu.y = (this.getContentSize().height/2) - this.Editbox.getContentSize().height;



        this.addChild(menu,1);
        this.addChild(this.Editbox,1);


        this.serverofflineLabel = new cc.LabelTTF("Server is down\ntry again in few seconds", "Arial",60);
        this.serverofflineLabel.x = cc.winSize.width/2;
        this.serverofflineLabel.y = (cc.winSize.height/2) - 200;
         
       
        this.parent.addChild(this.serverofflineLabel,3);
        this.serverofflineLabel.opacity = 0; 

 },
    editBoxTextChanged: function (editBox, text) {
        this.EditBoxText = text;
    },
    onMenuLogInCallback:function(sender){

        //send player name the server 
      this.serverofflineLabel.opacity = 0; 
      var msgProtocolObj = new MsgProtocol();
      msgProtocolObj.player_name = this.EditBoxText; 
      msgProtocolObj.end_player_pos_x=(winsize.width / 2).toString();
      msgProtocolObj.end_player_pos_y=(winsize.height / 2).toString();
      msgProtocolObj.status = 0;
      m_websocketMng.sendMassage(msgProtocolObj,this);
        
    },
    switchToGame:function()
    {
       this.parent.parent.switchTo(1);    
    },
 setXY:function (x,y) {
     this.x = x;
     this.y = y;
    }
});

Login.initSprite = function () {
    var login = new Login();
    return login;
};



Lines 33 - 38:initialize the background texture .
Lines 40 - 48:initialize the textbox
Lines 50 - 58:initialize the "LogIn" Button.
Lines 73 -83:In this callback function is triggered when pressing the "LogIn" button.
The MsgProtocol container is initialized and the player name and position and status is set.
Line:82:prepering the massage to be send to the server .
the game not switching right away to the GameLayer" it will first do validetion process of the new user in the WebSockets class ( the m_websocketMng object )
Lines 85 - 87: Switching to the "GameLayer scene" , this done after the player successfully validated in the server triggered from the WebSockets class  ( the m_websocketMng object) .


Continue to PART 5 client code where we examine Websockts.js


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