给skynet增加websocket模块
<p> 最近迷上了skynet,代码质量很高,算开源游戏服务器框架中的佼佼者,不管是Python的firefly,C++/Python的kbengine,C#的scut,还是nodejs的pomelo,skynet在并发上和商业应用都有很大的优势,根据http://thislinux.com/blog/5_panic.html描述,skynet能支持单机3w在线用户,性能很是给力。</p><p><br></p><p> 最近做的都是一些h5小游戏,用tornado/django基本上也都绰绰有余,下个小游戏打算试试skynet,skynet没有带websocket库,于是就很happy的去造轮子去了,虽然有lua-resty-websocket这个nginx扩展库,有2个原因我不喜欢。</p><p><br></p><p> 1.lua-resty-websocket实在太老了,现在已经是lua53的时代了</p><p><br></p><p> 2.还是喜欢tornado websocket的基于回调的方式,当然我写的既可使用回调方式,也可使用lua-resty-websocket</p><p><br></p><p>基于直接recv的方式</p><p><br></p><p> 其实解析websocket还是比较简单的,比较复杂点的是websocket 的close操作。和握手一样,close也是需要客户端-服务器</p><p><br></p><p>端确认的。</p><p><br></p><p> 当客户端->close ->服务端,服务端接收到opcode为8的close事件,服务端发送close frame,然后关闭客户端socket</p><p><br></p><p> 当服务端->close ->客户端,服务器发送close frame,此时客户端得到close事件,客户端接着会主动发送close frame给服务端,服务端接收到</p><p><br></p><p>opcode为8的close事件,关闭客户端socket。</p><p><br></p><p>这里需要注意,如果用js 的话,var ws = new WebSocket('XXXX'),在onclose事件中不需要主动调用ws.close(),底层会帮你调用。</p><p>local skynet = require "skynet"</p><p>local string = require "string"</p><p>local crypt = require "crypt"</p><p>local socket = require "socket"</p><p>local httpd = require "http.httpd"</p><p>local sockethelper = require "http.sockethelper"</p><p>local urllib = require "http.url"</p><p> </p><p>local ws = {}</p><p>local ws_mt = { __index = ws }</p><p> </p><p>local function response(id, ...)</p><p> return httpd.write_response(sockethelper.writefunc(id), ...)</p><p>end</p><p> </p><p> </p><p>local function write(id, data)</p><p> socket.write(id, data)</p><p>end</p><p> </p><p>local function read(id, sz)</p><p> return socket.read(id, sz)</p><p>end</p><p> </p><p> </p><p>local function challenge_response(key, protocol)</p><p> local accept = crypt.base64encode(crypt.sha1(key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))</p><p> return string.format("HTTP/1.1 101 Switching Protocols\r\n" ..</p><p> "Upgrade: websocket\r\n" ..</p><p> "Connection: Upgrade\r\n" ..</p><p> "Sec-WebSocket-Accept: %s\r\n" ..</p><p> "%s\r\n", accept, protocol or "")</p><p> </p><p>end</p><p> </p><p>local function accept_connection(header, check_origin, check_origin_ok)</p><p> -- Upgrade header should be present and should be equal to WebSocket</p><p> if not header["upgrade"] or header["upgrade"]:lower() ~= "websocket" then</p><p> return 400, "Can \"Upgrade\" only to \"WebSocket\"."</p><p> end</p><p> </p><p> -- Connection header should be upgrade. Some proxy servers/load balancers</p><p> -- might mess with it.</p><p> if not header["connection"] or not header["connection"]:lower():find("upgrade", 1,true) then</p><p> return 400, "\"Connection\" must be \"Upgrade\"."</p><p> end</p><p> </p><p> -- Handle WebSocket Origin naming convention differences</p><p> -- The difference between version 8 and 13 is that in 8 the</p><p> -- client sends a "Sec-Websocket-Origin" header and in 13 it's</p><p> -- simply "Origin".</p><p> local origin = header["origin"] or header["sec-websocket-origin"]</p><p> if origin and check_origin and not check_origin_ok(origin, header["host"]) then</p><p> return 403, "Cross origin websockets not allowed"</p><p> end</p><p> if not header["sec-websocket-version"] or header["sec-websocket-version"] ~= "13" then</p><p> return 400, "HTTP/1.1 Upgrade Required\r\nSec-WebSocket-Version: 13\r\n\r\n"</p><p> end</p><p> local key = header["sec-websocket-key"]</p><p> if not key then</p><p> return 400, "\"Sec-WebSocket-Key\" must not be nil."</p><p> end</p><p> local protocol = header["sec-websocket-protocol"] </p><p> if protocol then</p><p> local i = protocol:find(",", 1, true)</p><p> protocol = "Sec-WebSocket-Protocol: " .. protocol:sub(1, i or i-1)</p><p> end</p><p> return nil, challenge_response(key, protocol)</p><p>end</p><p>local H = {}</p><p>function H.check_origin_ok(origin, host)</p><p> return urllib.parse(origin) == host</p><p>end</p><p>function H.on_open(ws)</p><p> </p><p>end</p><p>function H.on_message(ws, message)</p><p> </p><p>end</p><p>function H.on_close(ws, code, reason)</p><p> </p><p>end</p><p>function H.on_pong(ws, data)</p><p> -- Invoked when the response to a ping frame is received.</p><p>end</p><p>function ws.new(id, header, handler, conf)</p><p> local conf = conf or {}</p><p> local handler = handler or {}</p><p> setmetatable(handler, { __index = H })</p><p> local code, result = accept_connection(header, conf.check_origin, handler.check_origin_ok)</p><p> if code then</p><p> response(id, code, result)</p><p> socket.close(id)</p><p> else</p><p> write(id, result)</p><p> end</p><p> local self = {</p><p> id = id,</p><p> handler = handler,</p><p> mask_outgoing = conf.mask_outgoing,</p><p> check_origin = conf.check_origin</p><p> }</p><p> self.handler.on_open(self)</p><p> </p><p> return setmetatable(self, ws_mt)</p><p>end</p><p>function ws:send_frame(fin, opcode, data)</p><p> if fin then</p><p> finbit = 0x80</p><p> else</p><p> finbit = 0</p><p> end</p><p> frame = string.pack("B", finbit | opcode)</p><p> l = #data</p><p> if self.mask_outgoing then</p><p> mask_bit = 0x80</p><p> else</p><p> mask_bit = 0</p><p> end</p><p> if l < 126 then</p><p> frame = frame .. string.pack("B", l | mask_bit)</p><p> elseif l < 0xFFFF then</p><p> frame = frame .. string.pack("!BH", 126 | mask_bit, l)</p><p> else </p><p> frame = frame .. string.pack("!BL", 127 | mask_bit, l)</p><p> end</p><p> if self.mask_outgoing then</p><p> end</p><p> frame = frame .. data</p><p> write(self.id, frame)</p><p> </p><p>end</p><p>function ws:send_text(data)</p><p> self:send_frame(true, 0x1, data)</p><p>end</p><p>function ws:send_binary(data)</p><p> self:send_frame(true, 0x2, data)</p><p>end</p><p>function ws:send_ping(data)</p><p> self:send_frame(true, 0x9, data)</p><p>end</p><p>function ws:send_pong(data)</p><p> self:send_frame(true, 0xA, data)</p><p>end</p><p>function ws:close(code, reason)</p><p> -- 1000 "normal closure" status code</p><p> if code == nil and reason ~= nil then</p><p> code = 1000</p><p> end</p><p> local data = ""</p><p> if code ~= nil then</p><p> data = string.pack(">H", code)</p><p> end</p><p> if reason ~= nil then</p><p> data = data .. reason</p><p> end</p><p> self:send_frame(true, 0x8, data)</p><p>end</p><p>function ws:recv()</p><p> local data = ""</p><p> while true do</p><p> local success, final, message = self:recv_frame()</p><p> if not success then</p><p> return success, message</p><p> end</p><p> if final then</p><p> data = data .. message</p><p> break</p><p> else</p><p> data = data .. message</p><p> end</p><p> end</p><p> self.handler.on_message(self, data)</p><p> return data</p><p>end</p><p>local function websocket_mask(mask, data, length)</p><p> umasked = {}</p><p> for i=1, length do</p><p> umasked = string.char(string.byte(data, i) ~ string.byte(mask, (i-1)%4 + 1))</p><p> end</p><p> return table.concat(umasked)</p><p>end</p><p>function ws:recv_frame()</p><p> local data, err = read(self.id, 2)</p><p> if not data then</p><p> return false, nil, "Read first 2 byte error: " .. err</p><p> end</p><p> local header, payloadlen = string.unpack("BB", data)</p><p> local final_frame = header & 0x80 ~= 0</p><p> local reserved_bits = header & 0x70 ~= 0</p><p> local frame_opcode = header & 0xf</p><p> local frame_opcode_is_control = frame_opcode & 0x8 ~= 0</p><p> if reserved_bits then</p><p> -- client is using as-yet-undefined extensions</p><p> return false, nil, "Reserved_bits show using undefined extensions"</p><p> end</p><p> local mask_frame = payloadlen & 0x80 ~= 0</p><p> payloadlen = payloadlen & 0x7f</p><p> if frame_opcode_is_control and payloadlen >= 126 then</p><p> -- control frames must have payload < 126</p><p> return false, nil, "Control frame payload overload"</p><p> end</p><p> if frame_opcode_is_control and not final_frame then</p><p> return false, nil, "Control frame must not be fragmented"</p><p> end</p><p> local frame_length, frame_mask</p><p> if payloadlen < 126 then</p><p> frame_length = payloadlen</p><p> elseif payloadlen == 126 then</p><p> local h_data, err = read(self.id, 2)</p><p> if not h_data then</p><p> return false, nil, "Payloadlen 126 read true length error:" .. err</p><p> end</p><p> frame_length = string.pack("!H", h_data)</p><p> else --payloadlen == 127</p><p> local l_data, err = read(self.id, 8)</p><p> if not l_data then</p><p> return false, nil, "Payloadlen 127 read true length error:" .. err</p><p> end</p><p> frame_length = string.pack("!L", l_data)</p><p> end</p><p> if mask_frame then</p><p> local mask, err = read(self.id, 4)</p><p> if not mask then</p><p> return false, nil, "Masking Key read error:" .. err</p><p> end</p><p> frame_mask = mask</p><p> end</p><p> --print('final_frame:', final_frame, "frame_opcode:", frame_opcode, "mask_frame:", mask_frame, "frame_length:", frame_length)</p><p> local frame_data = ""</p><p> if frame_length > 0 then</p><p> local fdata, err = read(self.id, frame_length)</p><p> if not fdata then</p><p> return false, nil, "Payload data read error:" .. err</p><p> end</p><p> frame_data = fdata</p><p> end</p><p> if mask_frame and frame_length > 0 then</p><p> frame_data = websocket_mask(frame_mask, frame_data, frame_length)</p><p> end</p><p> if not final_frame then</p><p> return true, false, frame_data</p><p> else</p><p> if frame_opcode == 0x1 then -- text</p><p> return true, true, frame_data</p><p> elseif frame_opcode == 0x2 then -- binary</p><p> return true, true, frame_data</p><p> elseif frame_opcode == 0x8 then -- close</p><p> local code, reason</p><p> if #frame_data >= 2 then</p><p> code = string.unpack(">H", frame_data:sub(1,2))</p><p> end</p><p> if #frame_data > 2 then</p><p> reason = frame_data:sub(3)</p><p> end</p><p> self:close()</p><p> socket.close(self.id)</p><p> self.handler.on_close(self, code, reason)</p><p> elseif frame_opcode == 0x9 then --Ping</p><p> self:send_pong()</p><p> elseif frame_opcode == 0xA then -- Pong</p><p> self.handler.on_pong(self, frame_data)</p><p> end</p><p> return true, true, nil</p><p> end</p><p>end</p><p>function ws:start()</p><p> while true do</p><p> local message, err = self:recv()</p><p> if not message then</p><p> --print('recv eror:', message, err)</p><p> socket.close(self.id)</p><p> end</p><p> end</p><p>end</p><p>return ws</p><p><br></p><p>是用方法也很简单,基于回调的方式用起来真是舒服</p><p><br></p><p>local skynet = require "skynet"</p><p>local socket = require "socket"</p><p>local string = require "string"</p><p>local websocket = require "websocket"</p><p>local httpd = require "http.httpd"</p><p>local urllib = require "http.url"</p><p>local sockethelper = require "http.sockethelper"</p><p> </p><p> </p><p>local handler = {}</p><p>function handler.on_open(ws)</p><p> print(string.format("%d::open", ws.id))</p><p>end</p><p> </p><p>function handler.on_message(ws, message)</p><p> print(string.format("%d receive:%s", ws.id, message))</p><p> ws:send_text(message .. "from server")</p><p>end</p><p> </p><p>function handler.on_close(ws, code, reason)</p><p> print(string.format("%d close:%d %s", ws.id, code, reason))</p><p>end</p><p> </p><p>local function handle_socket(id)</p><p> -- limit request body size to 8192 (you can pass nil to unlimit)</p><p> local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), 8192)</p><p> if code then</p><p> </p><p> if url == "/ws" then</p><p> local ws = websocket.new(id, header, handler)</p><p> ws:start()</p><p> end</p><p> end</p><p> </p><p> </p><p>end</p><p> </p><p>skynet.start(function()</p><p> local address = "0.0.0.0:8001"</p><p> skynet.error("Listening "..address)</p><p> local id = assert(socket.listen(address))</p><p> socket.start(id , function(id, addr)</p><p> socket.start(id)</p><p> pcall(handle_socket, id)</p><p> end)</p><p>end)</p><p><br></p><p>--------------------- </p><p>作者:yueguanghaidao </p><p>来源:CSDN </p><p>原文:https://blog.csdn.net/yueguanghaidao/article/details/45207059 </p><p><br></p><p></p>
页:
[1]