Skip to content

Instantly share code, notes, and snippets.

@EmielM
Created May 21, 2011 11:54
Show Gist options
  • Save EmielM/984461 to your computer and use it in GitHub Desktop.
Save EmielM/984461 to your computer and use it in GitHub Desktop.
class Protocol
constructor: ->
@recvCbs = []
@recvBuffer = new ByteBuffer
@socket = new Socket
@socket.onData = @onData.bind(this)
send: (buf) -> @socket.write(buf)
recv: (n, cb) -> @recvCbs.push({n: n, cb: cb})
onException: (msg) ->
console.error "protocol exception: #{msg}"
delete @recvBuffer, @recvCbs
@socket.close()
onData: (data) ->
@recvBuffer.pushBuf data
while @recvCbs[0] && @recvBuffer.length() >= @recvCbs[0].n
cb = @recvCbs.shift()
buf = @recvBuffer.splice(0, cb.n)
cb.cb(buf)
break if not @recvBuffer # exception during handling; break out
pingPong: ->
packet = new ByteBuffer
packet.pushString "PING"
@send packet
@recv 4, (packet) =>
string = packet.grabString()
return @onException("unexpected packet") if string != "PONG"
console.log "received pong"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment