Socket.IO の使いかた


こちらの記事にあるプログラムを改造してみました。
Socket.IOを使用して、サーバーからブラウザへデータを送信する

環境設定

mkdir socketio-simple
cd socketio-simple
npm init -y
npm i -S express node-cron socket.io

ソースファイルの作成

index.js
// ---------------------------------------------------------------
//  index.js
//
//                  May/20/2021
// ---------------------------------------------------------------
const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const cron = require('node-cron')

var count = 0

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html')
})

http.listen(3000, () => {
  console.log('listening on *:3000')
})

io.on('connection', (socket) => {
  console.log('a user connected')
  socket.on('disconnect', () => {
    console.log('user disconnected')
  })
})


cron.schedule('*/3 * * * * *', () => {
  const text_aa = 'hello ' + count

  console.log('send ' + text_aa)
  io.emit('message', text_aa)
  count += 1 
})

// ---------------------------------------------------------------
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<title>receive messages.</title>
</head>
<body>
    <ul id="messages"></ul>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script>
      jQuery( () => {
        const socket = io()
        socket.on('message', (msg) => {
          jQuery('#messages').append($('<li>').text(msg))
        })
      })
</script>
<hr />
May/20/2021 PM 20:20<br />
</body>
</html>

サーバーの起動

node index.js

ブラウザーで
[http://localhost:3000(http://localhost:3000)
にアクセス