日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Node.js笔记-使用socket.io构建websocket聊天室

發(fā)布時間:2025/3/15 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Node.js笔记-使用socket.io构建websocket聊天室 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

先安裝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">發(fā)送</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聊天室的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。