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.
- #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.
- Class Websockettestlayer:public Cocos2d::layer, public cocos2d::network::websocket::D elegate
and override the following 4 interfaces:
- virtual void OnOpen (cocos2d::network::websocket* ws);
- virtual void OnMessage (cocos2d::network::websocket* ws, const cocos2d::network::websocket::D ata& Data);
- virtual void OnClose (cocos2d::network::websocket* ws);
- 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:
- 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://".
- _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.
- void Websockettestlayer::onopen (network::websocket* ws)
- {
- if (ws = = _wsisendtext)
- {
- _sendtextstatus->setstring ("Send Text WS was opened.");
- }
- }
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.
- void Websockettestlayer::onmessage (network::websocket* ws, const network::websocket::D ata& Data)
- {
- if (!data.isbinary)
- {
- _sendtexttimes++;
- Char times[100] = {0};
- sprintf (Times, "%d", _sendtexttimes);
- std::string textstr = std::string ("Response text msg:") +data.bytes+ "," +times;
- Log ("%s", Textstr.c_str ());
- _sendtextstatus->setstring (Textstr.c_str ());
- }
- }
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.
- void Websockettestlayer::onclose (network::websocket* ws)
- {
- if (ws = = _wsisendtext)
- {
- _wsisendtext = NULL;
- }
- Cc_safe_delete (WS);
- }
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.
- void Websockettestlayer::onerror (network::websocket* ws, const network::websocket::errorcode& error)
- {
- Log ("error was fired, error code:%d", error);
- if (ws = = _wsisendtext)
- {
- Char buf[100] = {0};
- sprintf (buf, "An error is fired, code:%d", error);
- _sendtextstatus->setstring (BUF);
- }
- }
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
- _wsisendtext->send ("Hello WebSocket, I ' m a text message.");
Send binary data (more than one len parameter)
- _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.
- _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.
- 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.
- Local function Wssendtextopen (strdata)
- Sendtextstatus:setstring ("Send Text WS was opened.")
- End
- Local function wssendtextmessage (strdata)
- receivetexttimes= Receivetexttimes + 1
- Local strinfo= "Response text msg:". Strdata: ",". Receivetexttimes
- Sendtextstatus:setstring (Strinfo)
- End
- Local function Wssendtextclose (strdata)
- Print ("_wsisendtext websocket instance closed.")
- Sendtextstatus = Nil
- Wssendtext = Nil
- End
- Local function Wssendtexterror (strdata)
- Print ("SendText Error was fired")
- 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.
- If nil ~= Wssendtext then
- Wssendtext:registerscripthandler (WSSENDTEXTOPEN,CC. Websocket_open)
- Wssendtext:registerscripthandler (WSSENDTEXTMESSAGE,CC. Websocket_message)
- Wssendtext:registerscripthandler (WSSENDTEXTCLOSE,CC. Websocket_close)
- Wssendtext:registerscripthandler (WSSENDTEXTERROR,CC. Websocket_error)
- End
Send MessageThe following interfaces are used in LUA for sending text-insensitive or binary modes.
- 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.
- 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.
- 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.
- This._wsisendtext.onopen = function (evt) {
- Self._sendtextstatus.setstring ("Send Text WS was opened.");
- };
- This._wsisendtext.onmessage = function (evt) {
- self._sendtexttimes++;
- var textstr = "Response text msg:" +evt.data+ "," +self._sendtexttimes;
- Cc.log (TEXTSTR);
- Self._sendtextstatus.setstring (TEXTSTR);
- };
- This._wsisendtext.onerror = function (evt) {
- Cc.log ("SendText Error was fired");
- };
- This._wsisendtext.onclose = function (evt) {
- Cc.log ("_wsisendtext websocket instance closed.");
- Self._wsisendtext = null;
- };
Send MessageSend text without conversion, the code is as follows:
- 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.
- _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;
- },
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.
- var buf = "Hello websocket Chinese, +/-I ' m\0 a\0 binary\0 message\0.";
- var binary = This._stringconverttoarray (BUF);
- 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.
- Onexit:function () {
- if (This._wsisendtext)
- This._wsisendtext.close ();
- },
Transferred from: http://blog.sina.com.cn/s/blog_923fdd9b0101ggao.html