# 簡易 Websocket demo ## Server 端(node.js) 首先將以下 code 貼進名為 demo.js 的檔案(自己建立) ``` // 在伺服器端安裝 ws 模組 const WebSocket = require('ws'); // 建立 WebSocket 伺服器 const wss = new WebSocket.Server({ port: 8080 }); // 監聽 connection 事件,建立新的 WebSocket 連接 wss.on('connection', function connection(ws) { // 監聽 message 事件,接收客戶端發送的訊息 ws.on('message', function incoming(message) { // 將收到的訊息廣播給所有已連接的用戶 const msg = JSON.parse(message) wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(msg); } }); }); }); ``` ## Client 端 (javascript) 然後將以下 code 貼進 client.html (一樣自己建立) ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <input type="text" class="textbox" /> <button class="sendButton">send</button> <div class="chatWindow" style="width: 600px; height: 400px; background: #e0e0e0" ></div> </body> <script> // 建立 WebSocket 連接 const socket = new WebSocket('ws://localhost:8080'); const textbox = document.querySelector('.textbox'); const sendButton = document.querySelector('.sendButton'); const chatWindow = document.querySelector('.chatWindow'); // 監聽 message 事件,並在收到新訊息時將其顯示在聊天視窗中 socket.onmessage = function (event) { console.log(event); const message = event.data; chatWindow.innerHTML += '<p>' + message + '</p>'; }; // 當用戶輸入訊息並按下發送按鈕時,使用 send 方法將訊息發送到伺服器 sendButton.onclick = function () { const message = textbox.value; chatWindow.innerHTML += '<p>' + message + '</p>'; socket.send(message); }; </script> </html> ``` ## 啟動 **請記得一定要先啟動 nodejs server 再去做以下的事情!!** 啟動 liverserver 並打開兩個視窗,就可以互相傳訊息了,下方的灰匡會呈現即時聊天訊息
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up