码迷,mamicode.com
首页 > Web开发 > 详细

quick WebSocket

时间:2015-03-29 15:12:32      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:quick   websocket   使用   

将工程samples下的WebSockets工程的src/scenes 复制到自己的工程app/scenes/下
main.lua game.lua WebSockets.lua 复制到自己工程mian.lua同等级目录下,就可以运行了了。
其中使用到的接口函数

--connect阶段
function MainScene:onConnectClicked()
    if self.websocket then return end
    self.websocket = WebSockets.new("ws://echo.websocket.org")
    self.websocket:addEventListener(WebSockets.OPEN_EVENT, handler(self, self.onOpen))
    self.websocket:addEventListener(WebSockets.MESSAGE_EVENT, handler(self, self.onMessage))
    self.websocket:addEventListener(WebSockets.CLOSE_EVENT, handler(self, self.onClose))
    self.websocket:addEventListener(WebSockets.ERROR_EVENT, handler(self, self.onError))
end
--在调用send发送消息之前的4个消息回调 open、message、close、error
--onOpen如果链接成功,WebSocket就会调用onOpen,告诉调用者,客户端到服务器的通讯链路已经成功建立,可以收发消息了。
--onMessage 回传的消息
--onClose 不管是服务器主动还是被动关闭WebSocket,客户端将收到这个消息,需要做释放WebSocket内存置为nil操作
--onError客户端发送的请求,如果发生错误,就会收到onError消息,游戏根据不同的错误码,做出相应的处理。
function MainScene:onOpen(event)
    print("connected")
end

function MainScene:onMessage(event)
    if WebSockets.BINARY_MESSAGE == event.messageType then
        printf("receive binary msg: len = %s, binary = %s", string.len(event.message), bin2hex(event.message))
    else
        printf("receive text msg: %s", event.message)
    end
end

function MainScene:onClose(event)
    self.websocket = nil
end

function MainScene:onError(event)
    printf("error %s", event.error)
    self.websocket = nil
end
--发送text
function MainScene:onSendTextClicked()
    if not self.websocket then
        print("not connected")
        return
    end

    local text = "hello " .. tostring(math.random())
    if self.websocket:send(text) then
        printf("send text msg: %s", text)
    end
end
--发送binary
function MainScene:onSendBinaryClicked()
    if not self.websocket then
        print("not connected")
        return
    end

    local t = {}
    for i = 1, math.random(4, 8) do
        t[#t + 1] = string.char(math.random(0, 31))
    end
    local binary = table.concat(t)
    if self.websocket:send(binary, WebSockets.BINARY_MESSAGE) then
        printf("send binary msg: len = %d, binary = %s", string.len(binary), bin2hex(binary))
    end
end
--主动关闭webSocket(当不再使用websocket通讯时,调用close())

其中ws://echo.websocket.org是WebSocket.org 提供的一个专门用来测试WebSocket的服务器

quick WebSocket

标签:quick   websocket   使用   

原文地址:http://blog.csdn.net/u012102504/article/details/44726679

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!