Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

WebSocket protocol handler with pluggable I/O

License

NotificationsYou must be signed in to change notification settings

faye/websocket-driver-ruby

Repository files navigation

This module provides a complete implementation of the WebSocket protocols thatcan be hooked up to any TCP library. It aims to simplify things by decouplingthe protocol details from the I/O layer, such that users only need to implementcode to stream data in and out of it without needing to know anything about howthe protocol actually works. Think of it as a complete WebSocket system withpluggable I/O.

Due to this design, you get a lot of things for free. In particular, if you hookthis module up to some I/O object, it will do all of this for you:

  • Select the correct server-side driver to talk to the client
  • Generate and send both server- and client-side handshakes
  • Recognize when the handshake phase completes and the WS protocol begins
  • Negotiate subprotocol selection based onSec-WebSocket-Protocol
  • Negotiate and use extensions via thewebsocket-extensionsmodule
  • Buffer sent messages until the handshake process is finished
  • Deal with proxies that defer delivery of the draft-76 handshake body
  • Notify you when the socket is open and closed and when messages arrive
  • Recombine fragmented messages
  • Dispatch text, binary, ping, pong and close frames
  • Manage the socket-closing handshake process
  • Automatically reply to ping frames with a matching pong
  • Apply masking to messages sent by the client

This library was originally extracted from theFayeproject but now aims to provide simple WebSocket support for any Ruby server orI/O system.

Installation

$ gem install websocket-driver

Usage

To build either a server-side or client-side socket, the only requirement isthat you supply asocket object with these methods:

  • socket.url - returns the full URL of the socket as a string.
  • socket.write(string) - writes the given string to a TCP stream.

Server-side sockets require one additional method:

  • socket.env - returns a Rack-style env hash that will contain some of thefollowing fields. Their values are strings containing the value of the namedheader, unless stated otherwise.
    • HTTP_CONNECTION
    • HTTP_HOST
    • HTTP_ORIGIN
    • HTTP_SEC_WEBSOCKET_EXTENSIONS
    • HTTP_SEC_WEBSOCKET_KEY
    • HTTP_SEC_WEBSOCKET_KEY1
    • HTTP_SEC_WEBSOCKET_KEY2
    • HTTP_SEC_WEBSOCKET_PROTOCOL
    • HTTP_SEC_WEBSOCKET_VERSION
    • HTTP_UPGRADE
    • rack.input, anIO object representing the request body
    • REQUEST_METHOD, the request's HTTP verb

Server-side with Rack

To handle a server-side WebSocket connection, you need to check whether therequest is a WebSocket handshake, and if so create a protocol driver for it.You must give the driver an object with theenv,url andwrite methods. Asimple example might be:

require'websocket/driver'require'eventmachine'classWSattr_reader:env,:urldefinitialize(env)@env=envsecure=Rack::Request.new(env).ssl?scheme=secure ?'wss:' :'ws:'@url=scheme +'//' +env['HTTP_HOST'] +env['REQUEST_URI']@driver=WebSocket::Driver.rack(self)env['rack.hijack'].call@io=env['rack.hijack_io']EM.attach(@io,Reader){ |conn|conn.driver=@driver}@driver.startenddefwrite(string)@io.write(string)endmoduleReaderattr_writer:driverdefreceive_data(string)@driver.parse(string)endendend

To explain what's going on here: theWS class implements theenv,url andwrite(string) methods as required. When instantiated with a Rack environment,it stores the environment and infers the complete URL from it. Having set uptheenv andurl, it asksWebSocket::Driver for a server-side driver forthe socket. Then it uses the Rack hijack API to gain access to the TCP stream,and uses EventMachine to stream in incoming data from the client, handingincoming data off to the driver for parsing. Finally, we tell the driver tostart, which will begin sending the handshake response. This will invoke theWS#write method, which will send the response out over the TCP socket.

Having defined this class we could use it like this when handling a request:

ifWebSocket::Driver.websocket?(env)socket=WS.new(env)end

The driver API is described in full below.

Server-side with TCP

You can also handle WebSocket connections in a bare TCP server, if you're notusing Rack and don't want to implement HTTP parsing yourself. For this, yoursocket object only needs awrite method.

The driver will emit a:connect event when a request is received, and at thispoint you can detect whether it's a WebSocket and handle it as such. Here's anexample using an EventMachine TCP server.

moduleConnectiondefinitialize@driver=WebSocket::Driver.server(self)@driver.on:connect,->(event)doifWebSocket::Driver.websocket?(@driver.env)@driver.startelse# handle other HTTP requests, for examplebody='<h1>hello</h1>'response=['HTTP/1.1 200 OK','Content-Type: text/plain',"Content-Length:#{body.bytesize}",'',body]send_dataresponse.join("\r\n")endend@driver.on:message,->(e){@driver.text(e.data)}@driver.on:close,->(e){close_connection_after_writing}enddefreceive_data(data)@driver.parse(data)enddefwrite(data)send_data(data)endendEM.run{EM.start_server('127.0.0.1',4180,Connection)}

In the:connect event,@driver.env is a Rack env representing the request.If the request has a body, it will be in the@driver.env['rack.input'] stream,but only as much of the body as you have so far routed to it using theparsemethod.

Client-side

Similarly, to implement a WebSocket client you need an object withurl andwrite methods. Once you have one such object, you ask for a driver for it:

driver=WebSocket::Driver.client(socket)

After this you use the driver API as described below to process incoming dataand send outgoing data.

Client drivers have two additional methods for reading the HTTP data that wassent back by the server:

  • driver.status - the integer value of the HTTP status code
  • driver.headers - a hash-like object containing the response headers

HTTP Proxies

The client driver supports connections via HTTP proxies using theCONNECTmethod. Instead of sending the WebSocket handshake immediately, it will send aCONNECT request, wait for a200 response, and then proceed as normal.

To use this feature, callproxy = driver.proxy(url) whereurl is the originof the proxy, including a username and password if required. This produces anobject that manages the process of connecting via the proxy. You should callproxy.start to begin the connection process, and pass data you receive via thesocket toproxy.parse(data). When the proxy emits:connect, you should thenstart sending incoming data todriver.parse(data) as normal, and calldriver.start.

proxy=driver.proxy('http://username:password@proxy.example.com')proxy.on:connect,->(event)dodriver.startend

The proxy's:connect event is also where you should perform a TLS handshake onyour TCP stream, if you are connecting to awss: endpoint.

In the event that proxy connection fails,proxy will emit an:error. You caninspect the proxy's response viaproxy.status andproxy.headers.

proxy.on:error,->(error)doputserror.messageputsproxy.statusputsproxy.headers.inspectend

Before callingproxy.start you can set custom headers usingproxy.set_header:

proxy.set_header('User-Agent','ruby')proxy.start

Driver API

Drivers are created using one of the following methods:

driver=WebSocket::Driver.rack(socket,options)driver=WebSocket::Driver.server(socket,options)driver=WebSocket::Driver.client(socket,options)

Therack method returns a driver chosen using the socket'senv. Theservermethod returns a driver that will parse an HTTP request and then decide whichdriver to use for it using therack method. Theclient method always returnsa driver for the RFC version of the protocol with masking enabled on outgoingframes.

Theoptions argument is optional, and is a hash. It may contain the followingkeys:

  • :max_length - the maximum allowed size of incoming message frames, in bytes.The default value is2^26 - 1, or 1 byte short of 64 MiB.
  • :protocols - an array of strings representing acceptable subprotocols foruse over the socket. The driver will negotiate one of these to use via theSec-WebSocket-Protocol header if supported by the other peer.
  • :binary_data_format - in older versions of this library, binary messageswere represented as arrays of bytes, whereas they're now represented asstrings withEncoding::BINARY for performance reasons. Set this option to:array to restore the old behaviour.

All drivers respond to the following API methods, but some of them are no-opsdepending on whether the client supports the behaviour.

Note that most of these methods are commands: if they produce data that shouldbe sent over the socket, they will give this to you by callingsocket.write(string).

driver.on :open, -> (event) {}

Adds a callback block to execute when the socket becomes open.

driver.on :message, -> (event) {}

Adds a callback block to execute when a message is received.event will have adata attribute whose value is a string with the encodingEncoding::UTF_8 fortext message, andEncoding::BINARY for binary message.

driver.on :error, -> (event) {}

Adds a callback to execute when a protocol error occurs due to the other peersending an invalid byte sequence.event will have amessage attributedescribing the error.

driver.on :close, -> (event) {}

Adds a callback block to execute when the socket becomes closed. Theeventobject hascode andreason attributes.

driver.on :ping, -> (event) {}

Adds a callback block to execute when a ping is received. You do not need tohandle this by sending a pong frame yourself; the driver handles this for you.

driver.on :pong, -> (event) {}

Adds a callback block to execute when a pong is received. If this was inresponse to a ping you sent, you can also handle this event via thedriver.ping(message) { ... } callback.

driver.add_extension(extension)

Registers a protocol extension whose operation will be negotiated via theSec-WebSocket-Extensions header.extension is any extension compatible withthewebsocket-extensionsframework.

driver.set_header(name, value)

Sets a custom header to be sent as part of the handshake response, either fromthe server or from the client. Must be called beforestart, since this is whenthe headers are serialized and sent.

driver.start

Initiates the protocol by sending the handshake - either the response for aserver-side driver or the request for a client-side one. This should be thefirst method you invoke. Returnstrue if and only if a handshake was sent.

driver.parse(string)

Takes a string and parses it, potentially resulting in message events beingemitted (seeon('message') above) or in data being sent tosocket.write.You should send all data you receive via I/O to this method.

driver.text(string)

Sends a text message over the socket. If the socket handshake is not yetcomplete, the message will be queued until it is. Returnstrue if the messagewas sent or queued, andfalse if the socket can no longer send messages.

driver.binary(buffer)

Takes either a string with encodingEncoding::BINARY, or an array ofbyte-sized integers, and sends it as a binary message. Will queue and returntrue orfalse the same way as thetext method. It will also returnfalseif the driver does not support binary messages.

driver.ping(string = '', &callback)

Sends a ping frame over the socket, queueing it if necessary.string and thecallback block are both optional. If a callback is given, it will be invokedwhen the socket receives a pong frame whose content matchesstring. Returnsfalse if frames can no longer be sent, or if the driver does not supportping/pong.

driver.pong(string = '')

Sends a pong frame over the socket, queueing it if necessary.string isoptional. Returnsfalse if frames can no longer be sent, or if the driver doesnot support ping/pong.

You don't need to call this when a ping frame is received; pings are replied toautomatically by the driver. This method is for sending unsolicited pongs.

driver.close

Initiates the closing handshake if the socket is still open. For drivers with noclosing handshake, this will result in the immediate execution of theon('close') callback. For drivers with a closing handshake, this sends aclosing frame andemit('close') will execute when a response is received or aprotocol error occurs.

driver.version

Returns the WebSocket version in use as a string. Will either behixie-75,hixie-76 orhybi-$version.

driver.protocol

Returns a string containing the selected subprotocol, if any was agreed uponusing theSec-WebSocket-Protocol mechanism. This value becomes available afteremit('open') has fired.

About

WebSocket protocol handler with pluggable I/O

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors20


[8]ページ先頭

©2009-2025 Movatter.jp