Server 端分別能使用 send 發送訊息,以及透過監聽 message 事件接收來自 Client 的訊息:
// Connection opened
wss.on('connection', ws => {
console.log('[Client connected]')
// Listen for messages from client
ws.on('message', data => {
console.log('[Message from client]: ', data)
// Send message to client
ws.send('[Get message from server]')
})
// ...
})
1.3.4 Client 端:處理接發送 message
同樣的,Client 端也能使用 send 送出訊息,以及透過 onmessage 接收 Server 端的訊息:
// Listen for messages from Server
function sendMessage(msg) {
// Send messages to Server
ws.send(msg)
// Listen for messages from Server
ws.onmessage = event => console.log('[send message]', event)
}
1.4 實戰練習:實作一個簡單的即時聊天室
先前提到 WebSocket 常應用於即時聊天室等功能,也就是實現 Server 同時與多個 Client 連線。那該如何在 ClientA 傳送訊息給 Server 的同時,讓 ClientB 也接收到來自 Server 回傳的訊息呢?
// Connection opened
wss.on('connection', ws => {
console.log('[Client connected]')
// Listen for messages from client
ws.on('message', data => {
console.log('[Message from client]: ', data)
// Get clients who connected
let clients = wss.clients
// Use loop for sending messages to each client
clients.forEach(client => {
client.send('[Broadcast][Get message from server]')
})
})
// 建立 express 物件並用來監聽 8080 port
const server = express()
.listen(PORT, () => console.log(`[Server] Listening on https://localhost:${PORT}`))
// 建立實體,透過 ServerSocket 開啟 WebSocket 的服務
const wss = new ServerSocket({ server })
// Connection opened
wss.on('connection', (ws, req) => {
ws.id = req.headers['sec-websocket-key'].substring(0, 8)
ws.send(`[Client ${ws.id} is connected!]`)
// Listen for messages from client
ws.on('message', data => {
console.log('[Message from client] data: ', data)
// Get clients who has connected
let clients = wss.clients
// Use loop for sending messages to each client
clients.forEach(client => {
client.send(`${ws.id}: ` + data)
})
})