Skip to content

Instantly share code, notes, and snippets.

@josephg
Created October 6, 2011 14:01
Show Gist options
  • Save josephg/1267463 to your computer and use it in GitHub Desktop.
Save josephg/1267463 to your computer and use it in GitHub Desktop.
handler = new goog.net.BrowserChannel.Handler()
handler.channelOpened = (channel) =>
document.body.innerHTML += '<p>Connected</p>'
errors =
2: 'request failed'
6: 'unknown session id'
handler.channelError = (channel, error) =>
error = errors[error] if errors[error]
document.body.innerHTML += "<p>Channel error: #{error}</p>"
handler.channelClosed = (channel, pendingMaps, undeliveredMaps) =>
document.body.innerHTML += "<p>Disconnected</p>"
setTimeout (-> connect()), 3000
handler.channelHandleArray = (channel, msg) =>
console.log "channelHandleArray #{msg}" if console?
document.body.innerHTML += "<p>#{msg.date}</p>"
channel = null
# Send the time down the channel every 5 seconds
setInterval ->
if channel != null and channel.getState() is goog.net.BrowserChannel.State.OPENED
document.body.innerHTML += '<p>send</p>'
channel.sendMap {date:(new Date()).toString()}
, 5000
connect = ->
if channel
oldChannel = channel
channel.disconnect()
channel = new goog.net.BrowserChannel '1'
channel.setHandler handler
channel.setChannelDebug(new goog.net.ChannelDebug())
if oldChannel
channel.connect 'channel/test', 'channel/bind', null, oldChannel.getSessionId(), oldChannel.getLastArrayId()
else
channel.connect 'channel/test', 'channel/bind', null
connect()
browserChannel = require('..').server
connect = require 'connect'
clients = []
server = connect(
connect.static "#{__dirname}/public"
browserChannel (client) ->
console.log "Client #{client.id} connected"
clients.push client
client.on 'map', (data) ->
console.log "#{client.id} sent #{JSON.stringify data}"
# broadcast to all other clients
c.send data for c in clients when c != client
client.on 'close', (reason) ->
console.log "Client #{client.id} disconnected (#{reason})"
# Remove the client from the client list
clients = (c for c in clients when c != client)
).listen(4321)
console.log 'Echo server listening on localhost:4321'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment