ブロードキャストというのは、node.jsのサーバから接続されている各クライアントに配信することです。
プロジェクト作成
$ mkdir hoge $ cd hoge $ yarn add express $ yarn add socket.io $ vue create client $ cd client $ yarn add socket.io-client
とりあえず接続してみる
サーバー側
hoge/index.js
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); io.on('connection', function(socket){ console.log('a user connected'); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
クライアント側
hoge/client/src/App.vue
<template> <div id="app"> Hoge </div> </template> <script> import io from 'socket.io-client' export default { name: 'app', created () { const socket = io('http://localhost:3000') socket.on('connect', () => { console.log('connected!') }) socket.on('disconnect', () => { console.log('disconnected!') }) } } </script>
これでとりあえず接続されました。
ブロードキャストしてみる
サーバー側
hoge/index.js
const app = require('express')() const http = require('http').Server(app) const io = require('socket.io')(http) const calc = require('./calc') io.on('connection', socket => io.emit('hoge', 'connected!!')) http.listen(3000, () => console.log('listening on *:3000')) calc.calc(io)
hoge/calc.js
exports.calc = (io) => { setInterval(calc, 500) let count = 0 function calc() { count++ io.emit('hoge', count) } }
クライアント側
hoge/client/src/App.vue
<template> <div id="app"> Hoge </div> </template> <script> import io from 'socket.io-client' export default { name: 'app', created () { const socket = io('http://localhost:3000') socket.on('hoge', msg => console.log(msg)) } } </script>
これでブロードキャストできました!便利すぎ。