cocos2d-x-LuaProxy学习 C/S通信交互之WebSocket

C/S通信交互之WebSocket


      对于手游网络通信的交互,一般情况下,Socket长连接直接使用Mina框架即可,对于Http短连接使用Servlet 入口即可,那么本篇主要介绍Socket长连接,当然与此配对的跨平台通信则选择了WebSocket,当然还有其他的.

对于WebSocket不是很熟悉,可以参考WebSocket。本教程,主要讲怎样在客户端搭建websocket。


步骤一:


打开CCAppDelegate.cpp,添加头文件 #include "Lua_web_socket.h" , 在applicationDidFinishLaunching()添加如下代码:

[cpp]  view plain copy
  1.     CCLuaStack *pStack = pEngine->getLuaStack();  
  2.     lua_State* L = pStack->getLuaState();  
  3.       
  4. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)  
  5.     pStack = pEngine->getLuaStack();  
  6.     L = pStack->getLuaState();  
  7.     tolua_web_socket_open(L);  
  8. #endif  

步骤二:


编写lua测试代码,如下:

[cpp]  view plain copy
  1. -- for CCLuaEngine traceback  
  2.   
  3. function __G__TRACKBACK__(msg)  
  4. print("----------------------------------------")  
  5. print("LUA ERROR: " .. tostring(msg) .. "\n")  
  6. print(debug.traceback())  
  7. print("----------------------------------------")  
  8. end  
  9.   
  10. local function main()  
  11. -- avoid memory leak  
  12. --[[  
  13. collectgarbage("setpause", 100)  
  14. collectgarbage("setstepmul", 5000)  
  15.   
  16. local cclog = function(...)  
  17. print(string.format(...))  
  18. end  
  19.   
  20. require "hello2"  
  21. cclog("result is " .. myadd(3, 5))  
  22. ]]  
  23. ---------------  
  24.   
  25. --  
  26. local function createTest()  
  27.     local TestLayer = CCLayer:create()  
  28.     local proxy = LuaProxy:create()  
  29.     proxy:retain() -- hold the proxy, while the button gone, release the proxy.  
  30.     local n = proxy:readCCBFromFile("ccbResources/ccb/Test.ccbi") -- Got a CCNode  
  31.     local l = tolua.cast(n, "CCLayer") -- Cast the node into CCLayer  
  32.     TestLayer:addChild(l)  
  33.   
  34.     --winsocket  
  35.     local TestTxt = tolua.cast(proxy:getNode"TestTxt","CCLabelTTF")  
  36.     TestTxt:setString"web Socket"  
  37.       
  38.     local winSize = CCDirector:sharedDirector():getWinSize()  
  39.     local MARGIN = 40  
  40.     local SPACE  = 35  
  41.     local wsSendText   = nil  
  42.     local wsSendBinary = nil  
  43.     local wsError      = nil  
  44.     local sendTextStatus  = nil  
  45.     local sendBinaryStatus = nil  
  46.     local errorStatus  = nil  
  47.     local receiveTextTimes = 0  
  48.     local receiveBinaryTimes = 0  
  49.       
  50.     --Send Text  
  51.     local function onMenuSendTextClicked()  
  52.         if nil ~= wsSendText then  
  53.             if kStateOpen == wsSendText:getReadyState() then  
  54.                 sendTextStatus:setString("Send Text WS is waiting...")  
  55.                 wsSendText:sendTextMsg("Hello WebSocket中文, I'm a text message.")  
  56.             else  
  57.                 local warningStr = "send text websocket instance wasn't ready..."  
  58.                 print(warningStr)  
  59.                 sendTextStatus:setString(warningStr)  
  60.             end  
  61.         end  
  62.     end  
  63.   
  64.     --Send Binary  
  65.     local function onMenuSendBinaryClicked()  
  66.         if nil ~= wsSendBinary then  
  67.             if kStateOpen == wsSendBinary:getReadyState() then  
  68.                 sendBinaryStatus:setString("Send Binary WS is waiting...")  
  69.                 local buf = "Hello WebSocket中文--,\0 I'm\0 a\0 binary\0 message\0."  
  70.                 local nLength = string.len(buf)  
  71.                 t = {string.byte(buf,1,-1)}  
  72.                   
  73.                  wsSendBinary:sendBinaryMsg(t,table.getn(t))  
  74.             else  
  75.                 local warningStr = "send binary websocket instance wasn't ready..."  
  76.                 sendBinaryStatus:setString(warningStr)  
  77.             end  
  78.         end  
  79.     end  
  80.   
  81.   
  82.     --菜单  
  83.     --Send Text  
  84.     local menuTest = tolua.cast(proxy:getNode"menu","CCMenu")  
  85.       
  86.     local menuItemTest = proxy:getNode"menuTest","CCMenuItem"  
  87.     proxy:handleMenuEvent(menuItemTest,function()  
  88.         CCLuaLog("proxy:handleMenuEvent");  
  89.         onMenuSendTextClicked()  
  90.     end)  
  91.   
  92.     --Send Binary  
  93.     local menuItemTest1 = proxy:getNode"menuTest1","CCMenuItem"  
  94.     proxy:handleMenuEvent(menuItemTest1,function()  
  95.         CCLuaLog("proxy:handleMenuEvent");  
  96.         onMenuSendBinaryClicked();  
  97.     end)  
  98.   
  99.       
  100.     --设置文字显示内容  
  101.     local showNode1 = tolua.cast(proxy:getNode"showNode1","CCNode")  
  102.     local showNode2 = tolua.cast(proxy:getNode"showNode2","CCNode")  
  103.   
  104.     --Send Text Status Label  
  105.     sendTextStatus = tolua.cast(proxy:getNode"sendTextStatus","CCLabelTTF")  
  106.     sendTextStatus:setString"Send Text WS is waiting..."  
  107.     sendTextStatus:setDimensions(showNode1:getContentSize());  
  108.       
  109.     --Send Binary Status Label  
  110.     sendBinaryStatus = tolua.cast(proxy:getNode"sendBinaryStatus","CCLabelTTF")  
  111.     sendBinaryStatus:setString"Send Binary WS is waiting..."  
  112.     sendBinaryStatus:setDimensions(showNode2:getContentSize());  
  113.       
  114.      --Error Label  
  115.     errorStatus = tolua.cast(proxy:getNode"errorStatus","CCLabelTTF")  
  116.     errorStatus:setString"Error WS is waiting..."  
  117.       
  118.       
  119.     wsSendText   = WebSocket:create("ws://echo.websocket.org")  
  120.     wsSendBinary = WebSocket:create("ws://echo.websocket.org")  
  121.     wsError      = WebSocket:create("ws://localhost:8888/")  
  122.           
  123.     local function wsSendTextOpen(strData)  
  124.         sendTextStatus:setString("Send Text WS was opened.")  
  125.     end  
  126.       
  127.     local function wsSendTextMessage(strData)  
  128.         receiveTextTimes= receiveTextTimes + 1  
  129.         local strInfo= "response text msg: "..strData..", "..receiveTextTimes      
  130.         sendTextStatus:setString(strInfo)  
  131.     end  
  132.   
  133.     local function wsSendTextClose(strData)  
  134.         print("_wsiSendText websocket instance closed.")  
  135.         sendTextStatus = nil  
  136.         wsSendText = nil  
  137.     end  
  138.   
  139.     local function wsSendTextError(strData)  
  140.         print("sendText Error was fired")  
  141.     end  
  142.   
  143.     local function wsSendBinaryOpen(strData)  
  144.         sendBinaryStatus:setString("Send Binary WS was opened.")  
  145.     end  
  146.       
  147.     local function wsSendBinaryMessage(paramTable)  
  148.         local length = table.getn(paramTable)  
  149.         local i = 1  
  150.         local strInfo = "response bin msg: "  
  151.         for i = 1,length do  
  152.             if 0 == paramTable[i] then  
  153.                 strInfo = strInfo.."\'\\0\'"  
  154.             else  
  155.                 strInfo = strInfo..string.char(paramTable[i])  
  156.             end   
  157.         end  
  158.         receiveBinaryTimes = receiveBinaryTimes + 1  
  159.         strInfo = strInfo..receiveBinaryTimes  
  160.         sendBinaryStatus:setString(strInfo)  
  161.     end  
  162.       
  163.     local function wsSendBinaryClose(strData)  
  164.         print("_wsiSendBinary websocket instance closed.")  
  165.         sendBinaryStatus = nil  
  166.         wsSendBinary = nil  
  167.     end  
  168.   
  169.     local function wsSendBinaryError(strData)  
  170.         print("sendBinary Error was fired")  
  171.     end  
  172.   
  173.     local function wsErrorOpen(strData)  
  174.     end  
  175.   
  176.     local function wsErrorMessage(strData)  
  177.   
  178.     end  
  179.   
  180.     local function wsErrorError(strData)  
  181.         print("Error was fired")  
  182.         errorStatus:setString("an error was fired")  
  183.     end  
  184.   
  185.     local function wsErrorClose(strData)  
  186.         print("_wsiError websocket instance closed.")  
  187.         errorStatus= nil  
  188.         wsError = nil  
  189.     end  
  190.       
  191.     -- 注册wsSendText、wsSendBinary,wsError脚本处理函数  
  192.     if nil ~= wsSendText then  
  193.         wsSendText:registerScriptHandler(wsSendTextOpen,kWebSocketScriptHandlerOpen)  
  194.         wsSendText:registerScriptHandler(wsSendTextMessage,kWebSocketScriptHandlerMessage)  
  195.         wsSendText:registerScriptHandler(wsSendTextClose,kWebSocketScriptHandlerClose)  
  196.         wsSendText:registerScriptHandler(wsSendTextError,kWebSocketScriptHandlerError)  
  197.     end  
  198.   
  199.     if nil ~= wsSendBinary then  
  200.         wsSendBinary:registerScriptHandler(wsSendBinaryOpen,kWebSocketScriptHandlerOpen)  
  201.         wsSendBinary:registerScriptHandler(wsSendBinaryMessage,kWebSocketScriptHandlerMessage)  
  202.         wsSendBinary:registerScriptHandler(wsSendBinaryClose,kWebSocketScriptHandlerClose)  
  203.         wsSendBinary:registerScriptHandler(wsSendBinaryError,kWebSocketScriptHandlerError)  
  204.     end  
  205.   
  206.     if nil ~= wsError then  
  207.         wsError:registerScriptHandler(wsErrorOpen,kWebSocketScriptHandlerOpen)  
  208.         wsError:registerScriptHandler(wsErrorMessage,kWebSocketScriptHandlerMessage)  
  209.         wsError:registerScriptHandler(wsErrorClose,kWebSocketScriptHandlerClose)  
  210.         wsError:registerScriptHandler(wsErrorError,kWebSocketScriptHandlerError)  
  211.     end  
  212.   
  213.     local function OnExit(strEventName)  
  214.         if "exit" == strEventName then  
  215.             if nil ~= wsSendText  then  
  216.                 wsSendText:close()  
  217.             end  
  218.             if nil ~= wsSendBinary then  
  219.                 wsSendBinary:close()  
  220.             end  
  221.             if nil ~=  wsError     then  
  222.                 wsError:close()  
  223.             end  
  224.         end  
  225.     end  
  226.       
  227.       TestLayer:registerScriptHandler(OnExit)  
  228.       
  229.     return TestLayer  
  230. end  
  231.   
  232.   
  233.   
  234. -- run  
  235. local sceneGame = CCScene:create()  
  236.     sceneGame:addChild(createTest())  
  237.     CCDirector:sharedDirector():runWithScene(sceneGame)  
  238. end  
  239.   
  240. xpcall(main, __G__TRACKBACK__)  

运行效果图:





如有错误之处,希望大家多多纠正!


转载请注明出处:http://blog.csdn.net/rexuefengye/article/details/16803921



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值