Openresty + websocket + redissimplechat

Source: Internet
Author: User
Tags sendmsg
: This article mainly introduces openresty + websocket + redissimplechat. For more information about PHP tutorials, see.

Openresty has supported websocket for a long time, but the earlier versions of cosocket work independently. For more information about how to handle it, see websocket chat in the mail list. later versions of cosocket work on both sides, the websocket-based chat or push program can be implemented according to the solution discussed above, but no specific example is found on the network, so I wrote a simple example myself.

1. train of thought

After the websocket of the client is connected to openresty, usengx.thread.spawnStart twoLight threadOne is used to receive data submitted by the client and write it to the redis channel. The other is used to subscribe to the channel and read redis data to the client. A channel is equivalent to a chat room. multiple clients subscribe to it together. When someone sends a chat message (pub), everyone can get the information (sub ). The code is simple and easy to implement.

2. server code

Dependency:

  • Openresty
  • Redis
  • Lua-resty-redis
  • Lua-resty-websocket only supports RFC 6455

Nginx configuration is completely pasted, namely two locations, one is the page address and the other is the websocket address.

Configuration snippets

    location = /sredis {        content_by_lua_file conf/lua/ws_redis.lua;    }    location ~ /ws/(.*) {        alias conf/html/$1.html;    }

Lua code

-- Simple chat with redislocal server = require "resty. websocket. server "local redis = require" resty. redis "local channel_name =" chat "local msg_id = 0 -- create connectionlocal wb, err = server: new {timeout = 10000, max_payload_len = 65535} -- create successifnot wb then ngx. log (ngx. ERR, "failed to new websocket:", err) return ngx. exit (444) endlocal push = function () -- create redislocal red = redis: new () red: set_timeout (5000) -- 1 seclocal OK, err = red: connect ("127.0.0.1", 6379) ifnot OK then ngx. log (ngx. ERR, "failed to connect redis:", err) wb: send_close () returnend -- sublocal res, err = red: subscribe (channel_name) ifnot res then ngx. log (ngx. ERR, "failed to sub redis:", err) wb: send_close () returnend -- loop: read from rediswhiletruedolocal res, err = red: read_reply () if res thenlocal item = res [3] local bytes, err = wb: send_text (tostring (msg_id ).. "".. item) ifnot bytes then -- better error handling ngx. log (ngx. ERR, "failed to send text:", err) return ngx. exit (444) end msg_id = msg_id + 1 endendendlocal co = ngx. thread. spawn (push) -- main loopwhiletruedo -- get local data, typ, err = wb: recv_frame () -- Exit if wb if the connection is damaged. fatal then ngx. log (ngx. ERR, "failed to receive frame:", err) return ngx. exit (444) endifnot data thenlocal bytes, err = wb: send_ping () ifnot bytes then ngx. log (ngx. ERR, "failed to send ping:", err) return ngx. exit (444) end ngx. log (ngx. ERR, "send ping:", data) elseif typ = "close" thenbreakelseif typ = "ping" thenlocal bytes, err = wb: send_pong () ifnot bytes then ngx. log (ngx. ERR, "failed to send pong:", err) return ngx. exit (444) endelseif typ = "pong" then ngx. log (ngx. ERR, "client ponged") elseif typ = "text" then -- send to redislocal red2 = redis: new () red2: set_timeout (1000) -- 1 seclocal OK, err = red2: connect ("127.0.0.1", 6379) ifnot OK then ngx. log (ngx. ERR, "failed to connect redis:", err) breakendlocal res, err = red2: publish (channel_name, data) ifnot res then ngx. log (ngx. ERR, "failed to publish redis:", err) endendendwb: send_close () ngx. thread. wait (co)
3 page code

  
   
    
     
Var ws = null; functionWebSocketConn () {if (ws! = Null & ws. readyState = 1) {log ("already online"); return} if ("WebSocket" in window) {// Let us open a web socket ws = new WebSocket ("ws: // localhost: 8008/sredis"); ws. onopen = function () {log ('successfully entered the chatroom ') ;}; 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 WebSocket alert ("WebSocket NOT supported by your Browser! ") ;}} FunctionSendMsg () {if (ws! = Null & ws. readyState = 1) {var msg = document. getElementById ('msgtext '). value; ws. send (msg) ;}else {log ('Enter the chatroom first ') ;}} functionWebSocketClose () {if (ws! = Null & ws. readyState = 1) {ws. close (); log ("Send disconnect server request");} else {log ("no server currently connected")} functionlog (text) {var li = document. createElement ('Lil'); li. appendChild (document. createTextNode (text); document. getElementById ('log '). appendChild (li); returnfalse ;}
     
      
        Enter chat room
       
         Leave chat room
        


Send information

4. Effect

I tried it with the iphone. it may be due to the websocket version. Pc testing can be used normally.

Reading
  • Email 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) ;}) ;}; script

    The above introduces openresty + websocket + redis simple chat, including some content, and hope to be helpful to friends who are interested in PHP tutorials.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.