Last active
November 11, 2019 13:18
-
-
Save DezChuang/2198c42dbfef8e0bd4dd4d620deb3d41 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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