viernes, 18 de noviembre de 2016

WebSocketServer Cocos2djs - part 2 - c++ and javascript binding

This is the second blog entry where to explain what was the procedure i follow to create a native WebSocket Server for Cocos2dJs and examples to test it in android and ios.

In this second entry i'm going to explain a little bit about the c++ implementation of the Websocket server, the javascript binding and the javascript code that can be used.

(tested with cocos2djs 3.13.1)

Cocos2djs WebSocket Server

Websocket Server Implementation

The implementation comes from a copy of the files Websocket.h and Websocket.cpp from the same cocos2d-x. (cocos2d-x\cocos\network).
  • I get some ideas from https://github.com/mnisjk/cppWebSockets.
  • Used the same thread management than in Websocket client.
  • Created all callbacks to the server. 
  • Maintains a list of all the clients and their messages.
  • Create a delegate class with the methods onStart, onStop, onMessage, onConnection, onDisconnection.
  • I'm not a very skilled C++ developer so the thread and memory management can be improved. (Anyone that wants to contribute is welcome)

Javascript Binding

The implementation comes from a copy of the files jsb_websocket.h and jsb_websocket.cpp from the same cocos2d-x. (cocos2d-x\cocos\scriptting\js\network).

Javascript Api

The javascript api includes a class with following interface.

Class Name: WebSocketServer
Constructor: WebSocketServer(port, protocol) 
Methods:
  • stop()
  • send(clientId, message)
  • broadcast(message)
Listeners:
  • onServerUp()
  • onServerDown ()
  • onMessage(clientId, message)
  • onConnection(clientId)
  • onDiscconection(clientId)
  • onError(error)
Attributes:
  • readyState  (possible values are WebSocketServer.UP, WebSocketServer.DOWN, WebSocketServer.STARTING, WebSocketServerSTOPPING)



No hay comentarios:

Publicar un comentario