前言
源碼獲取:node+express+socket.io+web: 聊天demo (gitee.com)
目錄結構
后端依賴
啟動方式
前端是html正常啟動
后端是node app.js
后端app.js核心代碼
const express = require('express')
const app = express()
var http = require('http').Server(app)
var io = require('socket.io')(http, { cors: true })
var name = ""
var count = 0
app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next();
});
app.get('/',(req,res)=>{// 保存用戶的名稱name = req.query.username// 返回狀態碼,通過狀態碼執行客戶端頁面跳轉res.send({state:200})// res.sendFile(__dirname + '/index.html')
})
//入口函數,連接進程
io.on('connection', function (socket) {// 每建立連接一次,在線人數減一count++//這里是發送消息// on用來監聽客戶端message事件,回調函數處理。socket.on('message', function (msg) {// 如果在這里通過url解析的username來改變下面33行即將渲染的name,會出現異步問題。name還沒有賦值就被傳到客戶端// 所以通過ajax請求,先讓后端拿到username,然后再做提示信息的渲染console.log(msg.username+':'+ msg.inpval);// 將客戶端發送來的消息中轉給所有客戶端io.emit('message', msg)});// loginin是自定義事件,第二個參數返回數據對象用于渲染,用于登陸后向客戶端發送用戶登錄信息io.emit('loginin',{count,des:'溫馨提示:'+name+'加入聊天室'})//登陸后向客戶端發送用戶退出信息socket.on('disconnect', function () {// loginout是自定義事件,第二個參數返回數據對象用于渲染count--io.emit('loginout',{count,des:'溫馨提示:'+name+'用戶退出聊天室'})// 連接每斷開一次,在線人數減一})
});
http.listen(3000, function () {console.log('listening:3000')
})
html部分
<!doctype html>
<html><head><title>Socket.IO chat</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}.chat {width: 400px;margin: 0 auto;border: 1px solid #333;}.title {line-height: 30px;color: black;border-bottom: 1px solid #999;text-align: center;}.content {width: 100%;overflow: auto;height: 500px;}#messages li {list-style: none;padding: 5px;}#m {width: 80%;height: 30px;outline: none;color: #666}#btn {width: 20%;height: 30px;cursor: pointer;}.tips {width: 50%;margin: 4px auto;padding: 2px 5px;text-align: center;font-size: 8px;border-radius: 10px;background-color: #cfcfcf;color: #fff}.title #people {font-size: 8px;color: #999;}</style>
</head><body><div class="chat"><div class="title"><h3>聊天室<span id="people">(0)</span></h3></div><div class="content"><ul id="messages"></ul></div><input id="m" autocomplete="off" /><button id="btn">Send</button></div>
</body>
<script src="./static/dist/socket.io.js"></script>
<script>// 通過url獲取usernamevar test = window.location.href;var username = decodeURI(test.split("?username=")[1]);// 做個判斷if (localStorage.getItem('username') != '') {var socket = io('http://localhost:3000/')var btn = document.getElementById('btn')var ul = document.getElementById('messages')let cxt = document.getElementById('m')let people = document.getElementById('people')// 點擊send按鈕,把消息發送給服務器btn.onclick = function () {// 把登錄的用戶名和輸入框內容全部發送給服務器,讓服務器做一次廣播,才能同步用戶信息。socket.emit('message', { username, inpval: cxt.value })return false}//監聽服務器的廣播消息,同步用戶信息,msg就是點擊發送按鈕發送的用戶信息socket.on('message', function (msg) {// 每個客戶端將用戶的消息渲染var newli = document.createElement("li")newli.innerHTML = msg.username + ':' + msg.inpvalul.appendChild(newli)cxt.value = ''})// 服務器端監聽服務端建立連接發來的信息,用于渲染溫馨提示信息,msg是服務器返回廣播的用戶對象數據socket.on("loginin", function (msg) {// 生成用戶進入房間提示信息標簽let tip = document.createElement("p")tip.innerHTML = msg.des// 設置樣式tip.className = "tips"ul.appendChild(tip)// people是顯示當前聊天室人數people.innerHTML = '(' + msg.count + ')'})//服務器端監聽服務端建立連接發來的信息,msg是服務器返回廣播的用戶對象數據socket.on("loginout", function (msg) {// 生成用戶退出提示信息let tip = document.createElement("p")tip.innerHTML = msg.destip.className = "tips"ul.appendChild(tip)people.innerHTML = '(' + msg.count + ')'})} else {window.location.href = "/login.html"}</script></html>
聯系方式
v:13053025350,歡迎詢問,也歡迎接單選手>>>>>