WebSockets - ryantc94/Knights-of-Arthur GitHub Wiki

ws Library

  • notes...

Socket.IO

  • Primarily uses webSockets but falls back to polling if necessary.

Server API

  • Server mounts onto HTTP server
  • Steps
  1. Create Socket.IO server alongside HTTP server
  2. Define server behavior on connection
  3. Define what connection handler will do on certain events

Server Object

  • var socketServer = require('socket.io')({http server})
  • ^socketServer.on - registers a callback, that is passed a socket object (only connect event is passed a socket object?), during an event (is listening)
  • ^^ 'connect' someone connect to server
  • ^^ 'disconnect' someone disconnected from server
  • ^^ the passed in socket object has methods for it as well
  • ^^^ socket.on - custom event
  • ^^^ socket.emit - send a message to this client only
  • ^^^ socket.broadcast.emit - send a message to everyone but this client
  • ^^^ socket.id - socket session id / client id
  • ^socketServer.emit - sends a message to all connected clients (anything supported by JSON)

Client API

  • Library that allows interaction with the HTTP server
  • Steps
  1. Create socket object (which is an interface for webSocket server interaction)
  2. Send messages / triggered callbacks

Client Socket Object

  • var socket = io() - gives back a socket object
  • socket.on('event name', call back)
  • socket.emit('event name', message) - send message to server, can send back custom event
  • (I this emits are used inside on? [seems like it in versoza's notes as well])

Development

*The development server automatically serves up the client-side library at: /socket.io/socket.io.js


Extra Resources

  1. https://stackoverflow.com/questions/3329641/how-do-multiple-clients-connect-simultaneously-to-one-port-say-80-on-a-server
  2. https://www.valentinog.com/blog/socket-io-node-js-react/