项目作者: CandyMi

项目描述 :
Add a lua websocket library for the skynet game server framework.
高级语言: Lua
项目地址: git://github.com/CandyMi/skynet-lua-websocket.git
创建时间: 2019-06-21T09:48:56Z
项目社区:https://github.com/CandyMi/skynet-lua-websocket

开源协议:MIT License

下载


skynet-lua-websocket

Add a lua websocket library for the skynet game server framework.

Most of mobile apps use Websocket for communication, e.g: Wechat、H5、Web Service push.

A Simplify Websocket Server Example

The following usage examples will show you how to use skynet-websocket:

  1. -- main.lua for skynet start script.
  2. local skynet = require "skynet"
  3. local socket = require "skynet.socket"
  4. local wsserver = require "websocket.server"
  5. local ws = require "ws"
  6. skynet.start(function()
  7. local server = socket.listen("0.0.0.0", 8000, 128)
  8. socket.start(server, function(id, ipaddr)
  9. local wss = wsserver:new {
  10. fd = id,
  11. cls = ws,
  12. nodelay = true,
  13. }
  14. return wss:start()
  15. end)
  16. end)

We launch a socket server(listen 0.0.0.0:8000) And All client connections will be received via the socket.start callback.

Create a Websocket.server object for each connection in the callback function and manage all events using the Websocket.server object.

The websocket.server object requires a parameter of lua.websocket.class, the sample file is here.

  1. -- ws.lua is a lua.websocket.class sample file.
  2. local skynet = require "skynet"
  3. local class = require "class"
  4. local ws = class("ws")
  5. function ws:ctor (opt)
  6. self.ws = opt.ws -- websocket对象
  7. self.headers = opt.headers -- http headers
  8. self.send_masked = false -- 掩码(默认为false, 不建议修改或者使用)
  9. self.max_payload_len = 65535 -- 最大有效载荷长度(默认为65535, 不建议修改或者使用)
  10. end
  11. function ws:on_open ()
  12. self.state = true
  13. self.count = 1
  14. skynet.error("客户端已连接")
  15. end
  16. function ws:on_message (msg, type)
  17. -- 客户端消息
  18. skynet.error("客户端发送消息:", msg, type)
  19. self.ws:send(msg, type == 'binary')
  20. -- self.ws:close()
  21. end
  22. function ws:on_error (msg)
  23. -- 错误消息
  24. skynet.error("错误的消息:", msg)
  25. end
  26. function ws:on_close (msg)
  27. -- 清理数据
  28. skynet.error("客户端断开了连接:", msg)
  29. end
  30. return ws

To simplify the use of Websocket.server, we have defined four callback methods(must) for everyday use.

  • on_open, When the connection has been established.

  • on_message, When the server receives the message from the client.

  • on_error, When the protocol is wrong or other exceptions.

  • on_close, websocket.client or websocket.server actively disconnects(Usually used to clean up data).

    Open Chrome browser and install wsc.crx plugin to test it. Start enjoying it. (passcode: cgwr)

TODO

write websocket.client. :)

License

MIT License