[Cocos2d-x] How to transfer data via WebSocket Connection server in Cocos2d-x 3.x version

Source: Internet
Author: User

WebSocket

Start by creating a new empty folder that is installed with NPM nodejs-websocket :

NPM Install Nodejs-websocket  

New app.js File:

varWS = Require ("Nodejs-websocket"); Ws.createserver (function(conn) {Conn.on ("Text", function (str) {Console.log ("Get the message:"+STR); Conn.sendtext ("The server got the message"); }) Conn.on ("Close", function (code, Reason) {Console.log ("Connection closed");    }); Conn.on ("Error", function (code, Reason) {Console.log ("An Error!"); });}). Listen8001);

By node app.js starting, the server is set up.

Cocos2d-x
    • include the header file first in the header file:
 #include "network/websocket.h" 
    • implements the WebSocket delegate:
class  helloworld :  public cocos2d::layer,public cocos2d::network:: WebSocket::D elegate  
    • The function interfaces defined in the four delegates and a Socketclient object used to connect:
//For virtual function in WebSocket delegateVirtual voidOnOpen (cocos2d::network::websocket* ws);Virtual voidOnMessage (cocos2d::network::websocket* ws,ConstCocos2d::network::websocket::D ata& Data);Virtual voidOnClose (cocos2d::network::websocket* ws);Virtual voidOnError (cocos2d::network::websocket* ws,Constcocos2d::network::websocket::errorcode& error);//The WebSocket IO clientCocos2d::network::websocket* _wsiclient;
    • Initialize client:
_wsiclient = new Cocos2d::network::websocket (); _wsiclient->init (*this , );  
    • Implement these functions in the CPP file:
//Start Socket connectionvoidHelloworld::onopen (cocos2d::network::websocket* ws) {Cclog ("OnOpen");}//received a messagevoidHelloworld::onmessage (cocos2d::network::websocket* ws,ConstCocos2d::network::websocket::D ata& Data) {STD::stringTextstr = data.bytes;        Textstr.c_str (); Cclog (Textstr.c_str ());}//Connection offvoidHelloworld::onclose (cocos2d::network::websocket* ws) {if(ws = = _wsiclient)    {_wsiclient = NULL;    } cc_safe_delete (WS); Cclog ("OnClose");}//Error encounteredvoidHelloworld::onerror (cocos2d::network::websocket* ws,Constcocos2d::network::websocket::errorcode& error) {if(ws = = _wsiclient) {Charbuf[ -] = {0}; sprintf (BUF,"An error was fired, code:%d", error); } cclog ("error was fired, error code:%d", error);}

There is also a plan to use Socketio, not yet tried, test it tomorrow:

//Require HTTP module (to start server) and Socket.iovarHTTP = require (' http '), Io = require (' Socket.io ');//Start the server at port 8080varServer = Http.createserver (function(req, res) {//Send HTML headers and messageRes.writehead ( $,{' Content-type ':' text/html '}); Res.end (' );}); Server.listen (8080);//Create a Socket.io instance, passing it our servervarSocket = Io.listen (server);//ADD a Connect listenerSocket.on (' Connection ',function(client) {//Create periodical which ends a message to the client every 5 seconds    varInterval = SetInterval (function() {Client.send (' This was a message from the server! '+NewDate (). GetTime ()); }, the);//success! Now listen to messages to be receivedClient.on (' message ',function(event) {Console.log (' Received message from client! ', event);    }); Client.on (' Disconnect ',function() {clearinterval (interval); Console.log (' Server has disconnected '); });});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.