Node.js笔记-使用socket.io构建websocket聊天室
生活随笔
收集整理的這篇文章主要介紹了
Node.js笔记-使用socket.io构建websocket聊天室
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先安裝socket.io
npm install socket.io服務端代碼:
let app = require('http').createServer(); let io = require('socket.io')(app, { cors: true });let port = 3000; let clientCount = 0;app.listen(port);io.on('connection', function (socket) {clientCount++;socket.nickname = 'user' + clientCount;io.emit('enter', socket.nickname + ' comes in');socket.on('message', function (str) {io.emit('message', socket.nickname + ' says: ' + str);})socket.on('disconnect', function () {io.emit('leave', socket.nickname + ' left');}) });console.log("Websocket server listening on port = " + port)客戶端代碼:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>WebSocketIO</title><script src="https://cdn.socket.io/4.0.1/socket.io.js"></script> </head> <body><h1>Chat Room</h1><input id="sendTxt" type="text" /><button id="sendBtn">發送</button><script type="text/javascript">let socket = io("ws://localhost: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);}document.getElementById("sendBtn").onclick = function () {let txt = document.getElementById("sendTxt").value;if(txt){console.log(txt)socket.emit('message', txt);}}socket.on('enter', function (data) {showMessage(data, 'enter');})socket.on('message', function (data) {showMessage(data, 'message');})socket.on('leave', function (data) {showMessage(data, 'leave');})</script> </body> </html>運行截圖如下:
?退出:
總結
以上是生活随笔為你收集整理的Node.js笔记-使用socket.io构建websocket聊天室的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-Threaded Fo
- 下一篇: Qt文档阅读笔记-Simple Anch