[Node.js] Socket.io的Broadcast

由於Bingo遊戲要弄一個廣播叫號系統,試用了Broadcast如下。

Server

1
2
3
4
5
6
7
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.on('broadcastdata', function (data) {
socket.broadcast.emit('newdata', data);
});
});

Client

Host
1
2
3
4
5
6
7
8
9
10
11
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
function Send(msg)
{
socket.emit('broadcastdata', msg );
}
</script>
<input type="text" width ="200" id ="data" value = "" />
<input type="button" width ="100" value="Send" onclick="Send(data.value)"/>
Player
1
2
3
4
5
6
7
8
9
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<input type="text" width ="200" readonly = "true" id = "mytext" value="" />
<script>
var socket = io.connect('http://localhost:8080');
socket.on('newdata', function (data) {
document.getElementById("mytext").value = data ;
});
</script>