Skip to content

Instantly share code, notes, and snippets.

@kyubuns
Created September 12, 2012 19:21
Show Gist options
  • Save kyubuns/3709247 to your computer and use it in GitHub Desktop.
Save kyubuns/3709247 to your computer and use it in GitHub Desktop.
chat.coffeeたたき台
$ ->
if not "WebSocket" in window
alert "WebSocket NOT supported by your Browser!"
return
#-----ここからライブラリでやる-----
METHOD_IDS = {
'chatStoC' : 100,
'chatCtoS' : 200
}
class Connection
constructor: (host) ->
@method_caller = {}
@method_caller[METHOD_IDS['chatStoC']] = (args) =>
return if args.length isnt 2
@chatStoC(args[0], args[1])
socket = new WebSocket host
socket.binaryType = 'arraybuffer'
socket.onopen = (evt) => @onopen(evt)
socket.onclose = (evt) => @onclose(evt)
socket.onerror = (evt) => @onerror(evt)
socket.onmessage = (evt) =>
tmp = msgpack.unpack new Uint8Array evt.data
id = tmp[0]
args = tmp[1]
@method_caller[id](args) if @method_caller[id]
#call
@chatCtoS = (name, msg) =>
binary = msgpack.pack [METHOD_IDS['chatCtoS'], [name, msg]]
arraybuffer = new Uint8Array binary
socket.send arraybuffer.buffer
#callback
onopen: (evt) ->
onclose: (evt) ->
onerror: (evt) ->
chatStoC: (name, message) ->
#-----ここまでライブラリでやる-----
class Client extends Connection
onopen: (evt) ->
$('#chat').prepend 'connected'
onclose: (evt) ->
$('#chat').prepend 'clooooooooooooooooooooooose'
chatStoC: (name, message) ->
console.debug('receive')
$('#chat').prepend "<p>#{name} : #{message}</p>"
client = new Client "ws://localhost:9998"
$('#send').click ->
return if $('#message').val() is ''
client.chatCtoS($('#name').val(), $('#message').val())
$('#message').val ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment