Last active
January 2, 2016 21:48
-
-
Save ba0918/8365450 to your computer and use it in GitHub Desktop.
WebSocket試した
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
EventEmitter = require('events').EventEmitter | |
WebSocketServer = require('ws').Server | |
WebSocketClient = require 'ws' | |
class ChatServer | |
constructor: -> | |
@server = new WebSocketServer { port: 80 } | |
@server.on 'connection', @onConnection | |
console.log "started server." | |
onConnection: (socket) => | |
client = new ChatClient socket, this | |
client.on 'chat', @onChat | |
onChat: (client, data) => | |
@broadcast data | |
broadcast: (data) -> | |
for client in @server.clients then client.send data | |
class ChatClient extends EventEmitter | |
constructor: (@socket, @server) -> | |
EventEmitter.call this | |
@socket.on 'open', @onOpen | |
@socket.on 'message', @onMessage | |
@socket.on 'close', @onClose | |
@socket.on 'error', @onError | |
onOpen: => | |
console.log "connected." | |
onMessage: (data) => | |
console.log "received message. #{data}" | |
@emit 'chat', this, data | |
onClose: (code) => | |
console.log "[#{code}] disconnected." | |
onError: (reason, code) => | |
console.log "[#{code}] #{reason}" | |
send: (data) -> | |
@socket.send data | |
class Bot | |
address: "ws://localhost" | |
constructor: -> | |
@maxClients = 1000 | |
@sayMaxClients = 10 | |
@sayDelay = 1000 | |
run: -> | |
for number in [1..@maxClients] then @_create number | |
_create: (num) -> | |
client = new WebSocketClient @address | |
client.on 'open', => | |
console.log "[#{num}] connected." | |
if num <= @sayMaxClients | |
timer = setInterval => | |
message = { id: num, timestamp: (new Date).getTime() } | |
client.send JSON.stringify message | |
, @sayDelay | |
client.on 'message', (data) => | |
data = JSON.parse data | |
time = (new Date).getTime() - data.timestamp | |
console.log "[#{num}] id #{data.id} latency #{time} ms" | |
client.on 'close', (code) => | |
console.log "[#{num}][#{code}] disconnected." | |
client.on 'error', (reason, code) => | |
console.log "[#{num}][#{code}] #{reason}" | |
server = new ChatServer | |
bot = new Bot | |
bot.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment