 	chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
 	(chars[Math.floor(Math.random() * chars.length)] for x in [0...length]).join('')
 
+# Many thanks to Dennis for his StackOverflow answer: http://goo.gl/UDanx
+string2ArrayBuffer = (string, callback) ->
+  bb = new WebKitBlobBuilder()
+  bb.append(string)
+  f = new FileReader()
+  f.onload = (e) ->
+    callback(e.target.result)
+  f.readAsArrayBuffer(bb.getBlob())
+
+arrayBuffer2String = (buf, callback) ->
+  bb = new WebKitBlobBuilder()
+  bb.append(buf)
+  f = new FileReader()
+  f.onload = (e) ->
+    callback(e.target.result)
+  f.readAsText(bb.getBlob())
+
+arrayBufferToArrayOfLongs = (arrayBuffer) ->
+  longs = []
+  arrayBufferView = new Uint8Array(arrayBuffer)
+  for i in [0...arrayBufferView.length]
+    longs[i] = arrayBufferView[i]
+  longs
+
+arrayOfLongsToArrayBuffer = (longs) ->
+	ab = new ArrayBuffer longs.length
+	abView = new Uint8Array ab
+	for i in [0...longs.length]
+		abView[i] = longs[i]
+	ab
+
+toSocketData = (str, cb) ->
+	string2ArrayBuffer str, (ab) ->
+		cb arrayBufferToArrayOfLongs ab
+
+fromSocketData = (arr, cb) ->
+	ab = arrayOfLongsToArrayBuffer arr
+	arrayBuffer2String ab, cb
+
 class EventEmitter
 	on: (ev, cb) ->
 		@_listeners ?= {}

			if crlf?
				line = @data.slice(0, crlf-1)
				@data = @data.slice(crlf+1)
				console.log '<=', line.toString('utf8')
				@onCommand(parseCommand line)
			else
				break

	send: (args...) ->
		msg = makeCommand args...
		console.log('=>', msg[0...msg.length-2])
		@socket.write(msg)

	onCommand: (cmd) ->
		switch cmd.command

		@socket = new net.Socket
		@socket.on 'connect', => @onConnect()
		@socket.on 'data', (data) => @onData data
		@data = []

	connect: ->
		@socket.connect(@port, @server)
