Openresty very early support websocket, but the earlier version cosocket is simplex, it is more troublesome to deal with the mailing list discussion WebSocket Chat, later version cosocket is a dual-work, You can follow this discussion to implement a websocket-based chat, or a push program, but the network did not find a specific example, so I wrote a simple example.
1 ideas
After the client's websocket is connected to Openresty, it uses ngx.thread.spawn
a startup of two 轻线程
, one to receive the data submitted by the client to the channel of the Redis, and the other to subscribe to the channel and read the Redis data to the client. The channel corresponds to a chat room, multiple client subscriptions, a chat message (pub), and everyone gets the information (sub). The code is relatively humble, simple ideas to achieve.
2 Service-side code
Depend on:
- Openresty
- Redis
- Lua-resty-redis
- Lua-resty-websocket only supports RFC 6455
Nginx configuration All affixed, is two location, one is the page address, one is WebSocket address.
Configuring Fragments
{ content_by_lua_file conf/lua/ws_redis.lua; } { alias conf/html/$1.html; }
LUA Code
--Simple chat with RedisLocalServer =require"Resty.websocket.server"LocalRedis =require"Resty.redis"LocalChannel_name ="Chat"Localmsg_id =0--create ConnectionLocalWB, err = server:new{Timeout =10000, Max_payload_len =65535}--create Successif notWb ThenNgx.log (NGX. Err"Failed to new WebSocket:", err)returnNgx.exit (444)EndLocalPush = function() ----Create RedisLocalRed = Redis:new () red:set_timeout ( the)--1 SECLocalOK, err = Red:connect ("127.0.0.1",6379)if notOk ThenNgx.log (NGX. Err"Failed to connect Redis:", err) Wb:send_close ()returnEnd--subLocalRes, err = Red:subscribe (channel_name)if notRes ThenNgx.log (NGX. Err"Failed to sub Redis:", err) Wb:send_close ()returnEnd--Loop:read from Redis whiletrue DoLocalRes, err = red:read_reply ()ifRes ThenLocalitem = res[3]LocalBytes, err = Wb:send_text (ToString(msg_id):" ".. Itemif notbytes Then--Better error handlingNgx.log (NGX. Err"Failed to send text:", err)returnNgx.exit (444)Endmsg_id = msg_id +1EndEndEndLocalCO = ngx.thread.spawn (push)--main Loop whiletrue Do--Get DataLocalData, Typ, err = Wb:recv_frame ()--If the connection is damaged exitifWb.fatal ThenNgx.log (NGX. Err"failed to receive frame:", err)returnNgx.exit (444)Endif notData ThenLocalBytes, err = wb:send_ping ()if notbytes ThenNgx.log (NGX. Err"Failed to send ping:", err)returnNgx.exit (444)EndNgx.log (NGX. Err"Send ping:", data)ElseIfTyp = ="Close" Then BreakElseIfTyp = ="Ping" ThenLocalBytes, err = Wb:send_pong ()if notbytes ThenNgx.log (NGX. Err"failed to send pong:", err)returnNgx.exit (444)EndElseIfTyp = ="Pong" ThenNgx.log (NGX. Err"Client ponged")ElseIfTyp = ="Text" Then--send to RedisLocalRed2 = Redis:new () red2:set_timeout ( +)--1 SECLocalOK, err = Red2:connect ("127.0.0.1",6379)if notOk ThenNgx.log (NGX. Err"Failed to connect Redis:", err) BreakEndLocalRes, err = red2:publish (channel_name, data)if notRes ThenNgx.log (NGX. Err"failed to publish Redis:", err)EndEndEndWb:send_close () ngx.thread.wait (CO)
3 page code
<html><head><metacharset="Utf-8"><metaname="viewport"content="Width=device-width, initial-scale=1.0, User-scalable=no "><scripttype="Text/javascript">varWS =NULL; functionwebsocketconn() {if(ws! =NULL&& Ws.readystate = =1) {log ("Already online");return}if("WebSocket"inchwindow) {/Let us Open a Web socketWS =NewWebSocket ("Ws://localhost:8008/sredis"); Ws.onopen = function() {Log' successfully entered the chat room '); }; Ws.onmessage = function(event) {Log (Event.data)}; Ws.onclose = function() {//WebSocket is closed.Log"Disconnected from server"); }; Ws.onerror = function(event) {Console.log ("Error"+ Event.data); }; }Else{//The browser doesn ' t support WebSocketAlert"WebSocket not supported by your browser!"); } } functionsendmsg() {if(ws! =NULL&& Ws.readystate = =1) {varmsg = document.getElementById (' Msgtext '). Value; Ws.send (msg); }Else{log (' Please enter the chat room first '); } } functionwebsocketclose() {if(ws! =NULL&& Ws.readystate = =1) {ws.close (); Log"Send disconnect server request"); }Else{log ("No server currently connected") } } functionlog(text) {varLi = document.createelement (' Li '); Li.appendchild (document.createTextNode (text)); document.getElementById (' log '). AppendChild (LI);returnfalse; }
Script
>
Head
><body><divid="SSE"><ahref="Javascript:websocketconn ()">Enter the chat room
a
> <ahref="Javascript:websocketclose ()">Leave the chat room
a
><br><br><inputid="Msgtext"type="text"><br><ahref="javascript:sendmsg ()">Send Message
a
><br><olid="Log">
ol
>
Div
>
Body
>
HTML
>
4 effects
Using the iphone to try, not to work, may be the websocket version of the implementation of the problem. PC-side testing can be used normally.
Reading
- Mailing List Discussion WebSocket Chat
- Aapo Websocket with Openresty
'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
'). Text (i)); }; $numbering. FadeIn (1700); }); });
The above describes the Openresty+websocket+redis simple chat, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.