C/S通信交互之WebSocket
对于手游网络通信的交互,一般情况下,Socket长连接直接使用Mina框架即可,对于Http短连接使用Servlet 入口即可,那么本篇主要介绍Socket长连接,当然与此配对的跨平台通信则选择了WebSocket,当然还有其他的.
对于WebSocket不是很熟悉,可以参考WebSocket。本教程,主要讲怎样在客户端搭建websocket。
步骤一:
打开CCAppDelegate.cpp,添加头文件 #include "Lua_web_socket.h" , 在applicationDidFinishLaunching()添加如下代码:
- CCLuaStack *pStack = pEngine->getLuaStack();
- lua_State* L = pStack->getLuaState();
- #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
- pStack = pEngine->getLuaStack();
- L = pStack->getLuaState();
- tolua_web_socket_open(L);
- #endif
步骤二:
编写lua测试代码,如下:
- -- for CCLuaEngine traceback
- function __G__TRACKBACK__(msg)
- print("----------------------------------------")
- print("LUA ERROR: " .. tostring(msg) .. "\n")
- print(debug.traceback())
- print("----------------------------------------")
- end
- local function main()
- -- avoid memory leak
- --[[
- collectgarbage("setpause", 100)
- collectgarbage("setstepmul", 5000)
- local cclog = function(...)
- print(string.format(...))
- end
- require "hello2"
- cclog("result is " .. myadd(3, 5))
- ]]
- ---------------
- --
- local function createTest()
- local TestLayer = CCLayer:create()
- local proxy = LuaProxy:create()
- proxy:retain() -- hold the proxy, while the button gone, release the proxy.
- local n = proxy:readCCBFromFile("ccbResources/ccb/Test.ccbi") -- Got a CCNode
- local l = tolua.cast(n, "CCLayer") -- Cast the node into CCLayer
- TestLayer:addChild(l)
- --winsocket
- local TestTxt = tolua.cast(proxy:getNode"TestTxt","CCLabelTTF")
- TestTxt:setString"web Socket"
- local winSize = CCDirector:sharedDirector():getWinSize()
- local MARGIN = 40
- local SPACE = 35
- local wsSendText = nil
- local wsSendBinary = nil
- local wsError = nil
- local sendTextStatus = nil
- local sendBinaryStatus = nil
- local errorStatus = nil
- local receiveTextTimes = 0
- local receiveBinaryTimes = 0
- --Send Text
- local function onMenuSendTextClicked()
- if nil ~= wsSendText then
- if kStateOpen == wsSendText:getReadyState() then
- sendTextStatus:setString("Send Text WS is waiting...")
- wsSendText:sendTextMsg("Hello WebSocket中文, I'm a text message.")
- else
- local warningStr = "send text websocket instance wasn't ready..."
- print(warningStr)
- sendTextStatus:setString(warningStr)
- end
- end
- end
- --Send Binary
- local function onMenuSendBinaryClicked()
- if nil ~= wsSendBinary then
- if kStateOpen == wsSendBinary:getReadyState() then
- sendBinaryStatus:setString("Send Binary WS is waiting...")
- local buf = "Hello WebSocket中文--,\0 I'm\0 a\0 binary\0 message\0."
- local nLength = string.len(buf)
- t = {string.byte(buf,1,-1)}
- wsSendBinary:sendBinaryMsg(t,table.getn(t))
- else
- local warningStr = "send binary websocket instance wasn't ready..."
- sendBinaryStatus:setString(warningStr)
- end
- end
- end
- --菜单
- --Send Text
- local menuTest = tolua.cast(proxy:getNode"menu","CCMenu")
- local menuItemTest = proxy:getNode"menuTest","CCMenuItem"
- proxy:handleMenuEvent(menuItemTest,function()
- CCLuaLog("proxy:handleMenuEvent");
- onMenuSendTextClicked()
- end)
- --Send Binary
- local menuItemTest1 = proxy:getNode"menuTest1","CCMenuItem"
- proxy:handleMenuEvent(menuItemTest1,function()
- CCLuaLog("proxy:handleMenuEvent");
- onMenuSendBinaryClicked();
- end)
- --设置文字显示内容
- local showNode1 = tolua.cast(proxy:getNode"showNode1","CCNode")
- local showNode2 = tolua.cast(proxy:getNode"showNode2","CCNode")
- --Send Text Status Label
- sendTextStatus = tolua.cast(proxy:getNode"sendTextStatus","CCLabelTTF")
- sendTextStatus:setString"Send Text WS is waiting..."
- sendTextStatus:setDimensions(showNode1:getContentSize());
- --Send Binary Status Label
- sendBinaryStatus = tolua.cast(proxy:getNode"sendBinaryStatus","CCLabelTTF")
- sendBinaryStatus:setString"Send Binary WS is waiting..."
- sendBinaryStatus:setDimensions(showNode2:getContentSize());
- --Error Label
- errorStatus = tolua.cast(proxy:getNode"errorStatus","CCLabelTTF")
- errorStatus:setString"Error WS is waiting..."
- wsSendText = WebSocket:create("ws://echo.websocket.org")
- wsSendBinary = WebSocket:create("ws://echo.websocket.org")
- wsError = WebSocket:create("ws://localhost:8888/")
- 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
- local function wsSendBinaryOpen(strData)
- sendBinaryStatus:setString("Send Binary WS was opened.")
- end
- local function wsSendBinaryMessage(paramTable)
- local length = table.getn(paramTable)
- local i = 1
- local strInfo = "response bin msg: "
- for i = 1,length do
- if 0 == paramTable[i] then
- strInfo = strInfo.."\'\\0\'"
- else
- strInfo = strInfo..string.char(paramTable[i])
- end
- end
- receiveBinaryTimes = receiveBinaryTimes + 1
- strInfo = strInfo..receiveBinaryTimes
- sendBinaryStatus:setString(strInfo)
- end
- local function wsSendBinaryClose(strData)
- print("_wsiSendBinary websocket instance closed.")
- sendBinaryStatus = nil
- wsSendBinary = nil
- end
- local function wsSendBinaryError(strData)
- print("sendBinary Error was fired")
- end
- local function wsErrorOpen(strData)
- end
- local function wsErrorMessage(strData)
- end
- local function wsErrorError(strData)
- print("Error was fired")
- errorStatus:setString("an error was fired")
- end
- local function wsErrorClose(strData)
- print("_wsiError websocket instance closed.")
- errorStatus= nil
- wsError = nil
- end
- -- 注册wsSendText、wsSendBinary,wsError脚本处理函数
- if nil ~= wsSendText then
- wsSendText:registerScriptHandler(wsSendTextOpen,kWebSocketScriptHandlerOpen)
- wsSendText:registerScriptHandler(wsSendTextMessage,kWebSocketScriptHandlerMessage)
- wsSendText:registerScriptHandler(wsSendTextClose,kWebSocketScriptHandlerClose)
- wsSendText:registerScriptHandler(wsSendTextError,kWebSocketScriptHandlerError)
- end
- if nil ~= wsSendBinary then
- wsSendBinary:registerScriptHandler(wsSendBinaryOpen,kWebSocketScriptHandlerOpen)
- wsSendBinary:registerScriptHandler(wsSendBinaryMessage,kWebSocketScriptHandlerMessage)
- wsSendBinary:registerScriptHandler(wsSendBinaryClose,kWebSocketScriptHandlerClose)
- wsSendBinary:registerScriptHandler(wsSendBinaryError,kWebSocketScriptHandlerError)
- end
- if nil ~= wsError then
- wsError:registerScriptHandler(wsErrorOpen,kWebSocketScriptHandlerOpen)
- wsError:registerScriptHandler(wsErrorMessage,kWebSocketScriptHandlerMessage)
- wsError:registerScriptHandler(wsErrorClose,kWebSocketScriptHandlerClose)
- wsError:registerScriptHandler(wsErrorError,kWebSocketScriptHandlerError)
- end
- local function OnExit(strEventName)
- if "exit" == strEventName then
- if nil ~= wsSendText then
- wsSendText:close()
- end
- if nil ~= wsSendBinary then
- wsSendBinary:close()
- end
- if nil ~= wsError then
- wsError:close()
- end
- end
- end
- TestLayer:registerScriptHandler(OnExit)
- return TestLayer
- end
- -- run
- local sceneGame = CCScene:create()
- sceneGame:addChild(createTest())
- CCDirector:sharedDirector():runWithScene(sceneGame)
- end
- xpcall(main, __G__TRACKBACK__)
运行效果图:
如有错误之处,希望大家多多纠正!
转载请注明出处:http://blog.csdn.net/rexuefengye/article/details/16803921