=encoding utf-8


=head1 Name

lua-resty-websocket - Lua WebSocket implementation for the ngx_lua module


=head1 Status

This library is considered production ready.


=head1 Description

This Lua library implements a WebSocket server and client libraries based on the L<ngx_lua module|http://wiki.nginx.org/HttpLuaModule>.

This Lua library takes advantage of ngx_lua's cosocket API, which ensures
100% nonblocking behavior.

Note that only L<RFC 6455|http://tools.ietf.org/html/rfc6455> is supported. Earlier protocol revisions like "hybi-10", "hybi-07", and "hybi-00" are not and will not be considered.


=head1 Synopsis


        local server = require "resty.websocket.server"
    
        local wb, err = server:new{
            timeout = 5000,  -- in milliseconds
            max_payload_len = 65535,
        }
        if not wb then
            ngx.log(ngx.ERR, "failed to new websocket: ", err)
            return ngx.exit(444)
        end
    
        local data, typ, err = wb:recv_frame()
    
        if not data then
            if not string.find(err, "timeout", 1, true) then
                ngx.log(ngx.ERR, "failed to receive a frame: ", err)
                return ngx.exit(444)
            end
        end
    
        if typ == "close" then
            -- for typ "close", err contains the status code
            local code = err
    
            -- send a close frame back:
    
            local bytes, err = wb:send_close(1000, "enough, enough!")
            if not bytes then
                ngx.log(ngx.ERR, "failed to send the close frame: ", err)
                return
            end
            ngx.log(ngx.INFO, "closing with status code ", code, " and message ", data)
            return
        end
    
        if typ == "ping" then
            -- send a pong frame back:
    
            local bytes, err = wb:send_pong(data)
            if not bytes then
                ngx.log(ngx.ERR, "failed to send frame: ", err)
                return
            end
        elseif typ == "pong" then
            -- just discard the incoming pong frame
    
        else
            ngx.log(ngx.INFO, "received a frame of type ", typ, " and payload ", data)
        end
    
        wb:set_timeout(1000)  -- change the network timeout to 1 second
    
        bytes, err = wb:send_text("Hello world")
        if not bytes then
            ngx.log(ngx.ERR, "failed to send a text frame: ", err)
            return ngx.exit(444)
        end
    
        bytes, err = wb:send_binary("blah blah blah...")
        if not bytes then
            ngx.log(ngx.ERR, "failed to send a binary frame: ", err)
            return ngx.exit(444)
        end
    
        local bytes, err = wb:send_close(1000, "enough, enough!")
        if not bytes then
            ngx.log(ngx.ERR, "failed to send the close frame: ", err)
            return
        end




=head1 Modules




=head2 resty.websocket.server

To load this module, just do this


        local server = require "resty.websocket.server"




=head3 Methods





=head4 new

C<syntax: wb, err = server:new()>

C<syntax: wb, err = server:new(opts)>

Performs the websocket handshake process on the server side and returns a WebSocket server object.

In case of error, it returns C<nil> and a string describing the error.

An optional options table can be specified. The following options are as follows:


=over


=item *

C<max_payload_len>

Specifies the maximal length of payload allowed when sending and receiving WebSocket frames.

=item *

C<send_masked>

Specifies whether to send out masked WebSocket frames. When it is C<true>, masked frames are always sent. Default to C<false>.

=item *

C<timeout>

Specifies the network timeout threshold in milliseconds. You can change this setting later via the C<set_timeout> method call. Note that this timeout setting does not affect the HTTP response header sending process for the websocket handshake; you need to configure the L<send_timeout|http://nginx.org/en/docs/http/ngx_http_core_module.html#send_timeout> directive at the same time.


=back




=head4 set_timeout

C<syntax: wb:set_timeout(ms)>

Sets the timeout delay (in milliseconds) for the network-related operations.




=head4 send_text

C<syntax: bytes, err = wb:send_text(text)>

Sends the C<text> argument out as an unfragmented data frame of the C<text> type. Returns the number of bytes that have actually been sent on the TCP level.

In case of errors, returns C<nil> and a string describing the error.




=head4 send_binary

C<syntax: bytes, err = wb:send_binary(data)>

Sends the C<data> argument out as an unfragmented data frame of the C<binary> type. Returns the number of bytes that have actually been sent on the TCP level.

In case of errors, returns C<nil> and a string describing the error.




=head4 send_ping

C<syntax: bytes, err = wb:send_ping()>

C<syntax: bytes, err = wb:send_ping(msg)>

Sends out a C<ping> frame with an optional message specified by the C<msg> argument. Returns the number of bytes that have actually been sent on the TCP level.

In case of errors, returns C<nil> and a string describing the error.

Note that this method does not wait for a pong frame from the remote end.




=head4 send_pong

C<syntax: bytes, err = wb:send_pong()>

C<syntax: bytes, err = wb:send_pong(msg)>

Sends out a C<pong> frame with an optional message specified by the C<msg> argument. Returns the number of bytes that have actually been sent on the TCP level.

In case of errors, returns C<nil> and a string describing the error.




=head4 send_close

C<syntax: bytes, err = wb:send_close()>

C<syntax: bytes, err = wb:send_close(code, msg)>

Sends out a C<close> frame with an optional status code and a message.

In case of errors, returns C<nil> and a string describing the error.

For a list of valid status code, see the following document:

http://tools.ietf.org/html/rfc6455#section-7.4.1

Note that this method does not wait for a C<close> frame from the remote end.




=head4 send_frame

C<syntax: bytes, err = wb:send_frame(fin, opcode, payload)>

Sends out a raw websocket frame by specifying the C<fin> field (boolean value), the opcode, and the payload.

For a list of valid opcode, see

http://tools.ietf.org/html/rfc6455#section-5.2

In case of errors, returns C<nil> and a string describing the error.

To control the maximal payload length allowed, you can pass the C<max_payload_len> option to the C<new> constructor.

To control whether to send masked frames, you can pass C<true> to the C<send_masked> option in the C<new> constructor method. By default, unmasked frames are sent.




=head4 recv_frame

C<syntax: data, typ, err = wb:recv_frame()>

Receives a WebSocket frame from the wire.

In case of an error, returns two C<nil> values and a string describing the error.

The second return value is always the frame type, which could be one of C<continuation>, C<text>, C<binary>, C<close>, C<ping>, C<pong>, or C<nil> (for unknown types).

For C<close> frames, returns 3 values: the extra status message (which could be an empty string), the string "close", and a Lua number for the status code (if any). For possible closing status codes, see

http://tools.ietf.org/html/rfc6455#section-7.4.1

For other types of frames, just returns the payload and the type.

For fragmented frames, the C<err> return value is the Lua string "again".




=head2 resty.websocket.client

To load this module, just do this


        local client = require "resty.websocket.client"

A simple example to demonstrate the usage:


        local client = require "resty.websocket.client"
        local wb, err = client:new()
        local uri = "ws://127.0.0.1:" .. ngx.var.server_port .. "/s"
        local ok, err = wb:connect(uri)
        if not ok then
            ngx.say("failed to connect: " .. err)
            return
        end
    
        local data, typ, err = wb:recv_frame()
        if not data then
            ngx.say("failed to receive the frame: ", err)
            return
        end
    
        ngx.say("received: ", data, " (", typ, "): ", err)
    
        local bytes, err = wb:send_text("copy: " .. data)
        if not bytes then
            ngx.say("failed to send frame: ", err)
            return
        end
    
        local bytes, err = wb:send_close()
        if not bytes then
            ngx.say("failed to send frame: ", err)
            return
        end




=head3 Methods





=head4 client:new

C<syntax: wb, err = client:new()>

C<syntax: wb, err = client:new(opts)>

Instantiates a WebSocket client object.

In case of error, it returns C<nil> and a string describing the error.

An optional options table can be specified. The following options are as follows:


=over


=item *

C<max_payload_len>

Specifies the maximal length of payload allowed when sending and receiving WebSocket frames.

=item *

C<send_unmasked>

Specifies whether to send out an unmasked WebSocket frames. When it is C<true>, unmasked frames are always sent. Default to C<false>. RFC 6455 requires, however, that the client MUST send masked frames to the server, so never set this option to C<true> unless you know what you are doing.

=item *

C<timeout>

Specifies the default network timeout threshold in milliseconds. You can change this setting later via the C<set_timeout> method call.


=back




=head4 client:connect

C<< syntax: ok, err = wb:connect("ws://<host>:<port>/<path>") >>

C<< syntax: ok, err = wb:connect("wss://<host>:<port>/<path>") >>

C<< syntax: ok, err = wb:connect("ws://<host>:<port>/<path>", options) >>

C<< syntax: ok, err = wb:connect("wss://<host>:<port>/<path>", options) >>

Connects to the remote WebSocket service port and performs the websocket handshake process on the client side.

Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method.

An optional Lua table can be specified as the last argument to this method to specify various connect options:


=over


=item *

C<protocols>

Specifies all the subprotocols used for the current WebSocket session. It could be a Lua table holding all the subprotocol names or just a single Lua string.

=item *

C<origin>

Specifies the value of the C<Origin> request header.

=item *

C<pool>

Specifies a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template C<< <host>:<port> >>.

=item *

C<ssl_verify>

Specifies whether to perform SSL certificate verification during the
SSL handshake if the C<wss://> scheme is used.


=back

The SSL connection mode (C<wss://>) requires at least C<ngx_lua> 0.9.11 or OpenResty 1.7.4.1.




=head4 client:close

C<syntax: ok, err = wb:close()>

Closes the current WebSocket connection. If no C<close> frame is sent yet, then the C<close> frame will be automatically sent.




=head4 client:set_keepalive

C<syntax: ok, err = wb:set_keepalive(max_idle_timeout, pool_size)>

Puts the current WebSocket connection immediately into the C<ngx_lua> cosocket connection pool.

You can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process.

In case of success, returns C<1>. In case of errors, returns C<nil> with a string describing the error.

Only call this method in the place you would have called the C<close> method instead. Calling this method will immediately turn the current WebSocket object into the C<closed> state. Any subsequent operations other than C<connect()> on the current objet will return the C<closed> error.




=head4 client:set_timeout

C<syntax: wb:set_timeout(ms)>

Identical to the C<set_timeout> method of the C<resty.websocket.server> objects.




=head4 client:send_text

C<syntax: bytes, err = wb:send_text(text)>

Identical to the L<send_text> method of the C<resty.websocket.server> objects.




=head4 client:send_binary

C<syntax: bytes, err = wb:send_binary(data)>

Identical to the L<send_binary> method of the C<resty.websocket.server> objects.




=head4 client:send_ping

C<syntax: bytes, err = wb:send_ping()>

C<syntax: bytes, err = wb:send_ping(msg)>

Identical to the L<send_ping> method of the C<resty.websocket.server> objects.




=head4 client:send_pong

C<syntax: bytes, err = wb:send_pong()>

C<syntax: bytes, err = wb:send_pong(msg)>

Identical to the L<send_pong> method of the C<resty.websocket.server> objects.




=head4 client:send_close

C<syntax: bytes, err = wb:send_close()>

C<syntax: bytes, err = wb:send_close(code, msg)>

Identical to the L<send_close> method of the C<resty.websocket.server> objects.




=head4 client:send_frame

C<syntax: bytes, err = wb:send_frame(fin, opcode, payload)>

Identical to the L<send_frame> method of the C<resty.websocket.server> objects.

To control whether to send unmasked frames, you can pass C<true> to the C<send_unmasked> option in the C<new> constructor method. By default, masked frames are sent.




=head4 client:recv_frame

C<syntax: data, typ, err = wb:recv_frame()>

Identical to the L<recv_frame> method of the C<resty.websocket.server> objects.




=head2 resty.websocket.protocol

To load this module, just do this


        local protocol = require "resty.websocket.protocol"




=head3 Methods





=head4 recv_frame

C<syntax: data, typ, err = protocol.recv_frame(socket, max_payload_len, force_masking)>

Receives a WebSocket frame from the wire.




=head4 build_frame

C<syntax: frame = protocol.build_frame(fin, opcode, payload_len, payload, masking)>

Builds a raw WebSocket frame.




=head4 send_frame

C<syntax: bytes, err = protocol.send_frame(socket, fin, opcode, payload, max_payload_len, masking)>

Sends a raw WebSocket frame.




=head1 Automatic Error Logging

By default the underlying L<ngx_lua|http://wiki.nginx.org/HttpLuaModule> module
does error logging when socket errors happen. If you are already doing proper error
handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off L<ngx_lua|http://wiki.nginx.org/HttpLuaModule>'s L<lua_socket_log_errors|http://wiki.nginx.org/HttpLuaModule#lua_socket_log_errors> directive, that is,


        lua_socket_log_errors off;




=head1 Limitations


=over


=item *

This library cannot be used in code contexts like init_by_luaI<, set_by_lua>, log_by_lua*, and
header_filter_by_lua* where the ngx_lua cosocket API is not available.

=item *

The C<resty.websocket> object instance cannot be stored in a Lua variable at the Lua module level,
because it will then be shared by all the concurrent requests handled by the same nginx
worker process (see
http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker ) and
result in bad race conditions when concurrent requests are trying to use the same C<resty.websocket> instance.
You should always initiate C<resty.websocket> objects in function local
variables or in the C<ngx.ctx> table. These places all have their own data copies for
each request.


=back




=head1 Installation

It is recommended to use the latest L<OpenResty bundle|http://openresty.org> directly where this library
is bundled and enabled by default. At least OpenResty 1.4.2.9 is required. And you need to enable LuaJIT when building your OpenResty
bundle by passing the C<--with-luajit> option to its C<./configure> script. No extra Nginx configuration is required.

If you want to use this library with your own Nginx build (with ngx_lua), then
you need to ensure you are using at least ngx_lua 0.9.0
(and L<lua-bitop|http://bitop.luajit.org/> library if you are not using LuaJIT).
Also, You need to configure the
L<lua_package_path|https://github.com/chaoslawful/lua-nginx-module#lua_package_path>
directive to add the path of your lua-resty-websocket source tree to ngx_lua's
Lua module search path, as in


        # nginx.conf
        http {
            lua_package_path "/path/to/lua-resty-websocket/lib/?.lua;;";
            ...
        }

and then load the library in Lua:


        local server = require "resty.websocket.server"




=head1 TODO




=head1 Community




=head2 English Mailing List

The L<openresty-en|https://groups.google.com/group/openresty-en> mailing list is for English speakers.




=head2 Chinese Mailing List

The L<openresty|https://groups.google.com/group/openresty> mailing list is for Chinese speakers.




=head1 Bugs and Patches

Please report bugs or submit patches by


=over


=item 1.

creating a ticket on the L<GitHub Issue Tracker|http://github.com/agentzh/lua-resty-websocket/issues>,

=item 2.

or posting to the L<OpenResty community|http://wiki.nginx.org/HttpLuaModule#Community>.


=back




=head1 Author

Yichun "agentzh" Zhang (章亦春) E<lt>agentzh@gmail.comE<gt>, OpenResty Inc.




=head1 Copyright and License

This module is licensed under the BSD license.

Copyright (C) 2013-2017, by Yichun Zhang (agentzh) E<lt>agentzh@gmail.comE<gt>, OpenResty Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:


=over


=item *

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.


=back


=over


=item *

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.


=back

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.




=head1 See Also


=over


=item *

Blog post L<WebSockets with OpenResty|https://medium.com/p/1778601c9e05> by Aapo Talvensaari.

=item *

the ngx_lua module: http://wiki.nginx.org/HttpLuaModule

=item *

the websocket protocol: http://tools.ietf.org/html/rfc6455

=item *

the L<lua-resty-upload|https://github.com/agentzh/lua-resty-upload> library

=item *

the L<lua-resty-redis|https://github.com/agentzh/lua-resty-redis> library

=item *

the L<lua-resty-memcached|https://github.com/agentzh/lua-resty-memcached> library

=item *

the L<lua-resty-mysql|https://github.com/agentzh/lua-resty-mysql> library


=back



