"Go" "cocos2d-x Tutorial" how to use WebSocket

Source: Internet
Author: User
Tags sprintf

Introduced

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.

The engine supports the latest WebSocket Version 13.

Using in C + +

The detailed code can refer to the/samples/cpp/testcpp/classes/extensionstest/networktest/websockettest.cpp file under the engine directory.

Preparation in the header file

First, the Include WebSocket header file is required.

" 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  Public  public cocos2d::network::websocket::D elegate

and override the following 4 interfaces:

Virtual void onOpen (cocos2d::network::websocket* ws); Virtual void Const cocos2d::network::websocket::D ata& Data); Virtual void onClose (cocos2d::network::websocket* ws); Virtual void Const cocos2d::network::websocket::errorcode& error);

We'll go through the meaning of each callback interface in more detail later.

Create a new WebSocket and initialize

Websocket.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:

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 Monitoring

Before calling send for a message, look at the 4 message callbacks.

OnOpen

init triggers the websocket linked server, and if successful, WebSocket calls OnOpen, telling 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 ATA 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.

voidWebsockettestlayer::onmessage (network::websocket* ws,ConstNetwork::websocket::D ata&data) {    if(!data.isbinary) {_sendtexttimes++; Chartimes[ -] = {0}; sprintf (Times,"%d", _sendtexttimes); STD::stringTEXTSTR = std::string("Response text msg:") +data.bytes+", "+Times ; Log ("%s", Textstr.c_str ()); _sendtextstatus-setString (Textstr.c_str ()); }}

OnClose

Whether 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)    {        = NULL;    }    Cc_safe_delete (WS);}

OnError

The client sends the request, if an error occurs, it will receive the onerror message, the game for different error codes, to make corresponding processing.

voidWebsockettestlayer::onerror (network::websocket* ws,Constnetwork::websocket::errorcode&error) {Log ("error was fired, error code:%d", error); if(WS = =_wsisendtext) {        Charbuf[ -] = {0}; sprintf (BUF,"An error was fired, code:%d", error); _sendtextstatus-setString (BUF); }}

Send Message to Server

After 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)

Char sizeof (BUF));

Active shutdown WebSocket

This 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 Lua

The detailed code can refer to the/samples/lua/testlua/resources/luascript/extensiontest/webproxytest.lua file under the engine directory.

Create a WebSocket object

The 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 function

The callback function is normal LUA function,4 message callback and C + + uses the same, refer to the above description.

Local functionWssendtextopen (strdata) sendtextstatus:setstring ("Send Text WS was opened.")EndLocal functionwssendtextmessage (strdata) receivetexttimes= Receivetexttimes +1    Localstrinfo="Response text msg:".. Strdata.", ".. Receivetexttimes sendtextstatus:setstring (strinfo)EndLocal functionwssendtextclose (strdata)Print("_wsisendtext websocket instance closed.") Sendtextstatus=NilWssendtext=NilEndLocal functionwssendtexterror (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  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 Message

The 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 WebSocket

When 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_close message.

Wssendtext:close ()

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.