The author in learning WebSocket, write a simple demo.
The node-websocket package is used. Realize the multi-person chat function on the page. It’s not complicated…
Page code
<! 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> <h1>Chat Room</h1> <input type="text" id="sendTxt"> <button Id ="sendBtn" </button> <script> let websocket = new websocket ('ws://127.0.0.1:3000/'); function showMessage(str, type) { let div = document.createElement('div'); div.innerHTML = str; if (type === 'enter') { div.style.color = 'blue'; } else if (type === 'leave') { div.style.color = 'red' } document.body.appendChild(div); } websocket.onopen = function () { console.log('websocket open'); document.getElementById('sendBtn').onclick = function () { let txt = document.getElementById('sendTxt').value; if (txt) { websocket.send(txt) } } } websocket.onclose = function () { console.log('websocket close'); } websocket.onmessage = function (e) { console.log(e.data); let mes = JSON.parse(e.data) showMessage(mes.data, mes.type) } </script> </body> </html>Copy the code
The node service
let ws = require('nodejs-websocket')
let PORT = 3000
let clientCount = 0;
let server = ws.createServer(function (conn) {
console.log('New connection');
clientCount++
conn.nickname = 'user' + clientCount;
let mes = {};
mes.type = 'enter'
mes.data = conn.nickname + ' comes in'
broadcast(JSON.stringify(mes))
conn.on('text'.function (str) {
console.log('Received' + str);
let mes = {};
mes.type = 'message'
mes.data = conn.nickname + ' says: ' + str
broadcast(JSON.stringify(mes))
})
conn.on('close'.function (code, reason) {
console.log('Connection closed');
let mes = {};
mes.type = 'leave'
mes.data = conn.nickname + ' left'
broadcast(JSON.stringify(mes))
})
conn.on('error'.function (err) {
console.log('handle err');
console.log(err);
})
}).listen(PORT)
console.log('websocket server listening on port ' + PORT);
function broadcast(str) {
server.connections.forEach(function (connection) {
connection.sendText(str)
})
}
Copy the code
steps
The node wsServer. Js. Opening a different page next creates a new chat room member
Information about members entering and exiting chat rooms is displayed.