Skip to content

Instantly share code, notes, and snippets.

@EmielM
Created May 21, 2011 11:57
Show Gist options
  • Save EmielM/984464 to your computer and use it in GitHub Desktop.
Save EmielM/984464 to your computer and use it in GitHub Desktop.
class Protocol
constructor: ->
# ..same as previous snippet
@recvCbs.stack = [0] # pointer stack
recv: (n, cb) ->
# insert callback at pointer on stack
@recvCbs.splice(@recvCbs.stack[@recvCbs.stack.length-1], 0, {n: n, cb: cb})
@recvCbs.stack[@recvCbs.stack.length-1]++
onData: (data) ->
@recvBuffer.pushBuf data
while @recvCbs[0] && @recvBuffer.length() >= @recvCbs[0].n
cb = @recvCbs.shift()
buf = @recvBuffer.splice(0, cb.n)
@recvCbs.stack.push(0) # push pointer stack, @recv's added in cb.cb will be inserted here
cb.cb(buf) if cb.cb
break if not @recvBuffer? # exception during handling, break out
@recvCbs.stack.pop()
getCommand: ->
packet = new ByteBuffer
packet.pushString "HELLO"
@send packet
@recv 3, (packet) =>
command = packet.grabString()
switch command
when "EAT"
# expects a 5 byte specification of the food
@recv 5, (p) => console.log "eating #{p.grabString()}"
when "RUN"
# expects a 4 byte word of the speed
@recv 4, (p) => console.log "running #{p.grabInt()}"
when "MSG"
# expects a short with the length of the message,
# then the message
@recv 2, (p) =>
len = p.grabShort()
@recv len, (p) =>
console.log "message: #{p.grabString()}"
@recv 3, (packet) =>
string = packet.grabString()
return @onException("expected 'BYE'") if string != "BYE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment