ungoldman / choo-websocket

Small wraper around WebSocket browser API, for choo apps

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

choo-websocket stability

npm version build status downloads js-standard-style

Small wraper around WebSocket browser API, for choo apps

Usage

var choo = require('choo')
var html = require('choo/html')

var app = choo()
app.use(require('choo-websocket')())
app.route('/', mainView)
app.mount('body')

function mainView (state, emit) {
  return html`
    <body>
      <pre id="results"></pre>
      <p>Send something through sockets:</p>
      <input id="message" />
      <button onclick=${onclick}>Send</button>
    </body>
  `

  function onclick () {
    emit('ws:send', document.getElementById('message').value)
    document.getElementById('message').value = ''
  }
}

function live (state, emitter) {
  emitter.on('DOMContentLoaded', function () {
    emitter.on('ws:open', () => {
      console.log('Connection stablished')
    })
    emitter.on('ws:message', (data, event) => {
      var msgElement = document.getElementById('results')
      msgElement.textContent = msgElement.textContent + data + '\n'
    })
  })
}

Events

ws:error | ws.events.ERROR

Emitted if the WebSocket constructor or any of its methods throws an exception

ws:open | ws.events.OPEN

Emitted when the connection is stablished and the readyState property of the socket changes to OPEN

ws:close | ws.events.CLOSE

Emitted when the connection is close and the readyState property of the socket changes to CLOSED

ws:send | ws.events.SEND

Emitted to send a message through the socket

ws:message | ws.events.MESSAGE

Listen to this event to get messages from the socket

API

plugin = ws([route], [opts])

The plugin accept two optional parameters. You can pass the route for the web socket, default to window.location.host. Notice that you don't need to specify the ws protocol. Also you can pass some options as a second argument

  • secure: Boolean. Set to true if you are in a secure environment. If you mix environment, it will throw on creation of the socket.
  • protocols: Array or String. Use it to specify sub protocols for the socket.

If the object is correctly created, then you have a socket object in the state of your app with the following properties:

  • binaryType: A string describing the binary type of the transmited data. Either 'blob' or 'arraybuffer'.
  • bufferedAmount: The number of bytes of data that have been queued but not yet transmitted to the network.
  • extensions: The extensions selected by the server.
  • protocol: A string indicating the name of the sub-protocol the server selected.
  • state: The current state of the connection.
  • url: The URL as resolved by the constructor.

License

MIT

About

Small wraper around WebSocket browser API, for choo apps

License:MIT License


Languages

Language:JavaScript 100.0%