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

EventMachine based WebSocket server

License

NotificationsYou must be signed in to change notification settings

igrigorik/em-websocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gem VersionAnalytics

EventMachine based, async, Ruby WebSocket server. Take a look at examples directory, or check out the blog post:Ruby & Websockets: TCP for the Web.

Simple server example

require'em-websocket'EM.run{EM::WebSocket.run(:host=>"0.0.0.0",:port=>8080)do |ws|ws.onopen{ |handshake|puts"WebSocket connection open"# Access properties on the EM::WebSocket::Handshake object, e.g.# path, query_string, origin, headers# Publish message to the clientws.send"Hello Client, you connected to#{handshake.path}"}ws.onclose{puts"Connection closed"}ws.onmessage{ |msg|puts"Recieved message:#{msg}"ws.send"Pong:#{msg}"}end}

Protocols supported, and protocol specific functionality

Supports all WebSocket protocols in use in the wild (and a few that are not): drafts 75, 76, 1-17, rfc.

While some of the changes between protocols are unimportant from the point of view of application developers, a few drafts did introduce new functionality. It's possible to easily test for this functionality by using

Ping & pong supported

Callws.pingable? to check whether ping & pong is supported by the protocol in use.

It's possible to send a ping frame (ws.ping(body = '')), which the client must respond to with a pong, or the server can send an unsolicited pong frame (ws.pong(body = '')) which the client should not respond to. These methods can be used regardless of protocol version; they return true if the protocol supports ping&pong or false otherwise.

When receiving a ping, the server will automatically respond with a pong as the spec requires (so you shouldnot write an onping handler that replies with a pong), however it is possible to bind to ping & pong events if desired by using theonping andonpong methods.

Healthchecks

It's possible to send a regularHTTP GET request to the/healthcheck endpoint and receive a200 response from the server.

Close codes and reasons

A WebSocket connection can be closed cleanly, regardless of protocol, by callingws.close(code = nil, body = nil).

Early protocols just close the TCP connection, draft 3 introduced a close handshake, and draft 6 added close codes and reasons to the close handshake. Callws.supports_close_codes? to check whether close codes are supported (i.e. the protocol version is 6 or above).

Theonclose callback is passed a hash which may contain following keys (depending on the protocol version):

  • was_clean: boolean indicating whether the connection was closed via the close handshake.
  • code: the close code. There are two special close codes which the server may set (as defined in the WebSocket spec):
    • 1005: no code was supplied
    • 1006: abnormal closure (the same aswas_clean: false)
  • reason: the close reason

Acceptable close codes are defined in the WebSocket rfc (http://tools.ietf.org/html/rfc6455#section-7.4). The following codes can be supplies when callingws.close(code):

  • 1000: a generic normal close
  • range 3xxx: reserved for libraries, frameworks, and applications (and can be registered with IANA)
  • range 4xxx: for private use

If unsure use a code in the 4xxx range. em-websocket may also close a connection with one of the following close codes:

  • 1002: WebSocket protocol error.
  • 1009: Message too big to process. By default em-websocket will accept frames up to 10MB in size. If a frame is larger than this the connection will be closed without reading the frame data. The limit can be overriden globally (EM::WebSocket.max_frame_size = bytes) or on a specific connection (ws.max_frame_size = bytes).

Secure server

It is possible to accept securewss:// connections by passing:secure => true when opening the connection. Pass a:tls_options hash containing keys as described inhttp://www.rubydoc.info/github/eventmachine/eventmachine/EventMachine/Connection:start_tls

Warning: Safari 5 does not currently support prompting on untrusted SSL certificates therefore using a self signed certificate may leave you scratching your head.

EM::WebSocket.start({:host=>"0.0.0.0",:port=>443,:secure=>true,:tls_options=>{:private_key_file=>"/private/key",:cert_chain_file=>"/ssl/certificate"}})do |ws|# ...end

It's possible to check whether an incoming connection is secure by readinghandshake.secure? in the onopen callback.

Running behind an SSL Proxy/Terminator, like Stunnel

The:secure_proxy => true option makes it possible to use em-websocket behind a secure SSL proxy/terminator likeStunnel which does the actual encryption & decryption.

Note that this option is only required to support drafts 75 & 76 correctly (e.g. Safari 5.1.x & earlier, and Safari on iOS 5.x & earlier).

EM::WebSocket.start({:host=>"0.0.0.0",:port=>8080,:secure_proxy=>true})do |ws|# ...end

Handling errors

There are two kinds of errors that need to be handled -- WebSocket protocol errors and errors in application code.

WebSocket protocol errors (for example invalid data in the handshake or invalid message frames) raise errors which descend fromEM::WebSocket::WebSocketError. Such errors are rescued internally and the WebSocket connection will be closed immediately or an error code sent to the browser in accordance to the WebSocket specification. It is possible to be notified in application code of such errors by including anonerror callback.

ws.onerror{ |error|iferror.kind_of?(EM::WebSocket::WebSocketError)# ...end}

Application errors are treated differently. If noonerror callback has been defined these errors will propagate to the EventMachine reactor, typically causing your program to terminate. If you wish to handle exceptions, simply supply anonerror callback and check for exceptions which are not descendant fromEM::WebSocket::WebSocketError.

It is also possible to log all errors when developing by including the:debug => true option when initialising the WebSocket server.

Emulating WebSockets in older browsers

It is possible to emulate WebSockets in older browsers using flash emulation. For example take a look at theweb-socket-js project.

Using flash emulation does require some minimal support from em-websocket which is enabled by default. If flash connects to the WebSocket port and requests a policy file (which it will do if it fails to receive a policy file on port 843 after a timeout), em-websocket will return one. Also see#61 for an example policy file server which you can run on port 843.

Examples & Projects using em-websocket

  • Pusher - Realtime Messaging Service
  • Livereload - LiveReload applies CSS/JS changes to Safari or Chrome w/o reloading
  • Twitter AMQP WebSocket Example
  • examples/multicast.rb - broadcast all ruby tweets to all subscribers
  • examples/echo.rb - server <> client exchange via a websocket

About

EventMachine based WebSocket server

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors33

Languages


[8]ページ先頭

©2009-2025 Movatter.jp