使用WebSocket實作簡易聊天室(2)-實作+Node.js

Share This Post

Server 端 (Node.js)

  1. 啟一個 npm 專案並安裝套件

npm init -y
npm install express
npm install ws

  1. 建立 js 檔(server.js)
//import express 和 ws 套件
const express = require('express')
const SocketServer = require('ws').Server
const PORT = 3000 //指定 port

//創建 express 物件,綁定監聽  port , 設定開啟後在 console 中提示
const server = express().listen(PORT, () => {
    console.log(`Listening on ${PORT}`)
})
//將 express 交給 SocketServer 開啟 WebSocket 的服務
const wss = new SocketServer({ server })
//當有 client 連線成功時
wss.on('connection', ws => {
  console.log('Client connected')
  // 當收到client消息時
  ws.on('message', data => {
    // 收回來是 Buffer 格式、需轉成字串
    data = data.toString()  
    console.log(data) // 可在 terminal 看收到的訊息

    /// 發送消息給client 
    ws.send(data)

    /// 發送給所有client: 
    let clients = wss.clients  //取得所有連接中的 client
    clients.forEach(client => {
        client.send(data)  // 發送至每個 client
    })
  })
  // 當連線關閉
  ws.on('close', () => {
    console.log('Close connected')
  })
})

Client 端

  1. 建立 html 檔(index.html)(單純的頁面有 input 輸入框、submit 按鈕、能顯示文字的區塊即可)
<textarea id="txtShow" disabled></textarea>
<input id="txtInput" type="text">
<button id="btnSend">送出</button>
document.addEventListener("DOMContentLoaded", event => { 
  let keyinDom = document.querySelector('#txtInput')
  let showDom = document.querySelector('#txtShow')

  document.querySelector("#btnSend").addEventListener('click',() => {
    let txt = keyinDom.value;
    ws.send(txt);
  })

  // 建立 WebSocket (本例 server 端於本地運行)
  let url = 'ws://localhost:3000'
  var ws = new WebSocket(url)
  // 監聽連線狀態
  ws.onopen = () => {
    console.log('open connection')
  }
  ws.onclose = () => {
    console.log('close connection');
  }
  //接收 Server 發送的訊息
  ws.onmessage = event => {
    let txt = event.data
    if (!showDom.value) showDom.value = txt
    else showDom.value = showDom.value + "\n" + txt
    keyinDom.value = ""
  }
});

成果

訂閱研究文章

Get updates and learn from the best

More To Explore

Scroll to Top

hurry up !

軟體工程師培訓

限時免費報名中

藉由與「真實世界軟體專案」相同的技術、工具與開發流程,化簡成與商業機密無關、門檻較低更容易上手的「模擬專案」,讓你有機會在職場前輩的陪伴下,完成真槍實彈的練習,動手解決真實的問題,快速累積個人的經驗與作品,而不只是「學習技術」而已。