Skip to content

Instantly share code, notes, and snippets.

@takaheraw
Created April 28, 2013 12:50
Show Gist options
  • Save takaheraw/5476800 to your computer and use it in GitHub Desktop.
Save takaheraw/5476800 to your computer and use it in GitHub Desktop.
var WsServer = require('ws').Server;
var ws = new WsServer({host: 'localhost', port: 9005});
var con = {
clientLen : function() {
return ws.clients.length;
},
broadcast: function(msg) {
ws.clients.forEach(function(client) {
client.send(JSON.stringify(msg));
});
}
}
ws.on('connection', function(socket) {
socket.on('message', function(message) {
try {
var msg = JSON.parse(message);
con.broadcast(msg);
} catch (e) {
socket.send('JSONで送ってください');
}
});
});
<input id="msg"><button id="send">送信</button>
<div id="chat"></div>
<script>
var ws = new WebSocket('ws://localhost:9005');
ws.onmessage = function(msg) {
chat.innerHTML += '<hr>' + JSON.parse(msg.data);
}
send.onclick = function() {
ws.send(JSON.stringify(msg.value));
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment