Cocos2d-x WebSocket

Source: Internet
Author: User
Tags lua sprintf

WebSocket is a network technology that HTML5 started to provide full duplex communication between the browser and the server. In the WebSocket API, the browser and server only need to do a handshake, and then a fast channel is formed between the browser and the server. The data can be transmitted to each other directly between the two.

The Cocos2d-x engine integrates libwebsockets, and encapsulates an easy-to-use interface on the basis of Libwebsockets's client API, making it easy for the engine to communicate with the game network using WebSocket in C + +, JS, and LUA layers.

First, the Include WebSocket header file is required.
    1. #include "Network/websocket.h"
Cocos2d::network::websocket::D elegate defines a callback notification interface that uses Webscocket to listen. With WebSocket classes, public is required to inherit this delegate.
    1. Class Websockettestlayer:public Cocos2d::layer, public cocos2d::network::websocket::D elegate
and override the following 4 interfaces:
    1. virtual void OnOpen (cocos2d::network::websocket* ws);
    2. virtual void OnMessage (cocos2d::network::websocket* ws, const cocos2d::network::websocket::D ata& Data);
    3. virtual void OnClose (cocos2d::network::websocket* ws);
    4. virtual void OnError (cocos2d::network::websocket* ws, const cocos2d::network::websocket::errorcode& error);
We'll go through the meaning of each callback interface in more detail later. new WebSocket and initializeWebsocket.org provides a server dedicated to testing WebSocket "ws://echo.websocket.org". Test the code to link to this server for example, showing how to use WebSocket in Cocos2d-x. Create a new websocket:
    1. cocos2d::network::websocket* _wsisendtext = new Network::websocket ();
The first parameter of Init is delegate, set to this, and the second parameter is the server address. The "ws://" identifier in the URL is the WebSocket protocol, and the encrypted WebSocket is "wss://".
    1. _wsisendtext->init (*this, "ws://echo.websocket.org")
websocket Message MonitoringBefore calling send for a message, look at the 4 message callbacks. OnOpen InitTriggers the websocket linked server, and if successful, WebSocket invokes the OnOpen, tells the caller that the client-to-server communication link has been successfully established and can send and receive messages.
    1. void Websockettestlayer::onopen (network::websocket* ws)
    2. {
    3. if (ws = = _wsisendtext)
    4. {
    5. _sendtextstatus->setstring ("Send Text WS was opened.");
    6. }
    7. }
OnMessage network::websocket::D ataThe object stores the data received by the client, the IsBinary property is used to determine whether the data is binary or text, Len describes the length of the data, and bytes points to the data.
  1. void Websockettestlayer::onmessage (network::websocket* ws, const network::websocket::D ata& Data)
  2. {
  3. if (!data.isbinary)
  4. {
  5. _sendtexttimes++;
  6. Char times[100] = {0};
  7. sprintf (Times, "%d", _sendtexttimes);
  8. std::string textstr = std::string ("Response text msg:") +data.bytes+ "," +times;
  9. Log ("%s", Textstr.c_str ());
  10. _sendtextstatus->setstring (Textstr.c_str ());
  11. }
  12. }
OnCloseWhether the server is active or passive shut down the WebSocket, the client will receive this request, need to release websocket memory, and develop a good habit: null pointer.
    1. void Websockettestlayer::onclose (network::websocket* ws)
    2. {
    3. if (ws = = _wsisendtext)
    4. {
    5. _wsisendtext = NULL;
    6. }
    7. Cc_safe_delete (WS);
    8. }
OnErrorThe client sends the request, if an error occurs, it will receive the onerror message, the game for different error codes, to make corresponding processing.
    1. void Websockettestlayer::onerror (network::websocket* ws, const network::websocket::errorcode& error)
    2. {
    3. Log ("error was fired, error code:%d", error);
    4. if (ws = = _wsisendtext)
    5. {
    6. Char buf[100] = {0};
    7. sprintf (buf, "An error is fired, code:%d", error);
    8. _sendtextstatus->setstring (BUF);
    9. }
    10. }
send message to serverAfter Init, we can call the Send interface to send data requests to the server. Send has both text and binary modes. Send text
    1. _wsisendtext->send ("Hello WebSocket, I ' m a text message.");
Send binary data (more than one len parameter)
    1. _wsisendbinary->send (unsigned char*) buf, sizeof (BUF));
Active shutdown WebSocketThis is a critical step in making the whole process complete, and when a websocket communication is no longer in use, we have to manually turn off the WebSocket connection to the server. Close triggers the OnClose message, and then onclose inside, we release the memory.
    1. _wsisendtext->close ();
using in LuaThe detailed code can refer to the/samples/lua/testlua/resources/luascript/extensiontest/webproxytest.lua file under the engine directory. Create a WebSocket objectThe scripting interface is much simpler than C + +, there is no header file, and creating a WebSocket object is done using the following line of code. The parameter is the server address.
    1. Wssendtext = Websocket:create ("ws://echo.websocket.org")
defining and registering a message callback functionThe callback function is normal LUA function,4 message callback and C + + uses the same, refer to the above description.
  1. Local function Wssendtextopen (strdata)
  2. Sendtextstatus:setstring ("Send Text WS was opened.")
  3. End
  4. Local function wssendtextmessage (strdata)
  5. receivetexttimes= Receivetexttimes + 1
  6. Local strinfo= "Response text msg:". Strdata: ",". Receivetexttimes
  7. Sendtextstatus:setstring (Strinfo)
  8. End
  9. Local function Wssendtextclose (strdata)
  10. Print ("_wsisendtext websocket instance closed.")
  11. Sendtextstatus = Nil
  12. Wssendtext = Nil
  13. End
  14. Local function Wssendtexterror (strdata)
  15. Print ("SendText Error was fired")
  16. End
LUA's message registration differs from C + + inheritance & Override, with a separate interface Registerscripthandler. Registerscripthandler The first parameter is the callback function name, and the second argument is the callback type. Each of the WebSocket instances needs to be bound once.
    1. If nil ~= Wssendtext then
    2. Wssendtext:registerscripthandler (WSSENDTEXTOPEN,CC. Websocket_open)
    3. Wssendtext:registerscripthandler (WSSENDTEXTMESSAGE,CC. Websocket_message)
    4. Wssendtext:registerscripthandler (WSSENDTEXTCLOSE,CC. Websocket_close)
    5. Wssendtext:registerscripthandler (WSSENDTEXTERROR,CC. Websocket_error)
    6. End
Send MessageThe following interfaces are used in LUA for sending text-insensitive or binary modes.
    1. Wssendtext:sendstring ("Hello websocket Chinese, I ' m a text message.")
Active shutdown WebSocketWhen a websocket communication is no longer in use, we must manually shut down this websocket connection to the server to free up the resources of the server and the client. Close will trigger cc. Websocket_closeNews.
    1. Wssendtext:close ()
use in JSBThe detailed code can refer to the/samples/javascript/shared/tests/extensionstest/networktest/websockettest.js file under the engine directory. Create a WebSocket objectThe scripting interface is much simpler than C + +, there is no header file, and creating a WebSocket object is done using the following line of code. The parameter is the server address.
    1. This._wsisendtext = new WebSocket ("ws://echo.websocket.org");
set the message callback functionThe callback function in JSB is a property of the WebSocket instance and is directly assigned to the corresponding property using an anonymous function. You can see the features of the JS language and make the binding callback function more graceful. The meaning of the four callbacks, refer to the above C + + description.
  1. This._wsisendtext.onopen = function (evt) {
  2. Self._sendtextstatus.setstring ("Send Text WS was opened.");
  3. };
  4. This._wsisendtext.onmessage = function (evt) {
  5. self._sendtexttimes++;
  6. var textstr = "Response text msg:" +evt.data+ "," +self._sendtexttimes;
  7. Cc.log (TEXTSTR);
  8. Self._sendtextstatus.setstring (TEXTSTR);
  9. };
  10. This._wsisendtext.onerror = function (evt) {
  11. Cc.log ("SendText Error was fired");
  12. };
  13. This._wsisendtext.onclose = function (evt) {
  14. Cc.log ("_wsisendtext websocket instance closed.");
  15. Self._wsisendtext = null;
  16. };
Send MessageSend text without conversion, the code is as follows:
    1. This._wsisendtext.send ("Hello websocket Chinese, I ' m a text message.");
Send binary, test code, use the _stringconverttoarray function to convert a string into binary data, to simulate the sending of binary. New Uint16array creates a typed array of 16-bit unsigned integer values, and the contents are initialized to 0. Then, loop through the Unicode encoding of each character of the string, and deposit uint16array, and eventually get a binary object.
    1. _stringconverttoarray:function (strdata) {
    2. if (!strdata)
    3. return null;
    4. var arrdata = new Uint16array (strdata.length);
    5. for (var i = 0; i < strdata.length; i++) {
    6. Arrdata[i] = strdata.charcodeat (i);
    7. }
    8. return arrdata;
    9. },
The Send binary interface and the send text are not different, the difference lies in the incoming object, JS internal know whether the object is text or binary data, and then do different processing.
    1. var buf = "Hello websocket Chinese, +/-I ' m\0 a\0 binary\0 message\0.";
    2. var binary = This._stringconverttoarray (BUF);
    3. This._wsisendbinary.send (Binary.buffer);
Active shutdown WebSocketWhen a websocket communication is no longer in use, we must manually shut down this websocket connection to the server to free up the resources of the server and the client. Close will trigger the OnClose message.
    1. Onexit:function () {
    2. if (This._wsisendtext)
    3. This._wsisendtext.close ();
    4. },

Transferred from: http://blog.sina.com.cn/s/blog_923fdd9b0101ggao.html

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.