Skip to content

Instantly share code, notes, and snippets.

@DezChuang
Last active November 11, 2019 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DezChuang/2198c42dbfef8e0bd4dd4d620deb3d41 to your computer and use it in GitHub Desktop.
Save DezChuang/2198c42dbfef8e0bd4dd4d620deb3d41 to your computer and use it in GitHub Desktop.
const express = require('express')
const wsServer = require('ws').Server
const PORT = 5566
// 建立 express 物件並綁定在 port 5566
const server = express().listen(PORT, () => {
console.log(`Listening on ${PORT}`)
})
const wss = new wsServer({ server })
// 監聽是否有新的 client 連上線
wss.on('connection', ws => {
console.log('One client has connected.')
// 監聽 client 傳來的訊息後,再將訊息傳回去
ws.on('message', data => {
ws.send(data)
})
// 監聽 client 是否已經斷開連線
ws.on('close', () => {
console.log('One client has disconnected.')
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment