程式的流程圖: 主要代碼: 服務端 app.js 先載入所需要的通信模塊: 創建用戶列表和消息列表: 綁定並監聽80埠: 客戶端連接成功後,觸發響應事件connection,完成要綁定的事件並實現客戶端出發的事件: 客戶端 index.js: 先初始化用戶信息: 然後連接伺服器端: 連接成功後,對 ...
程式的流程圖:
主要代碼:
服務端 app.js
先載入所需要的通信模塊:
var express = require('express'); var app = express(); var http = require('http').createServer(app); var io = require('socket.io').listen(http); var fs = require('fs');
創建用戶列表和消息列表:
var person = []; var history = [];
綁定並監聽80埠:
app.get('/',function (req,res) { res.sendFile(__dirname + '/login.html'); }); http.listen(80,function () { console.log('listening on *:80'); });
客戶端連接成功後,觸發響應事件connection,完成要綁定的事件並實現客戶端出發的事件:
io.sockets.on('connection',function (socket) { var user = ''; socket.emit('history', history); io.sockets.emit('updatePerson', person); socket.on('sendMsg', function (data) { var obj = {}; obj.content = data; obj.time = now(); obj.name = user; if (history.length === history_num) { history.shift(); } history.push(obj); io.sockets.emit('news', obj); }); socket.on('setUserName', function (data) { user = data; person.push(user); io.sockets.emit('loginsucess'); io.sockets.emit('updatePerson', person); io.sockets.emit('news', {content: user + '進入房間', time: now(), name: '系統消息'}); }); socket.on('disconnect', function () { if (user !== '') { person.forEach(function (value, index) { if (value === user) { person.splice(index, 1); } }); io.sockets.emit('news', {content: user + '離開房間', time: now(), name: '系統消息'}); io.sockets.emit('updatePerson', person); } }); });
客戶端 index.js:
先初始化用戶信息:
$scope.data = []; //消息隊列 $scope.name = ''; //用戶名 $scope.content = ''; //用戶輸入的消息 $scope.personlist = []; //用戶隊列
然後連接伺服器端:
const socket_url = 'http://localhost'; var socket = io.connect(socket_url);
連接成功後,對用戶昵稱輸入的驗證:
$scope.checkName = function () { if($scope.name!==''){ if($scope.personlist.length!==0){ if($scope.personlist.indexOf($scope.name)>-1) { document.getElementById("info").textContent = "該昵稱已被占用,請重新輸入"; } else{ socket.emit('setUserName', $scope.name); } } else{ socket.emit('setUserName', $scope.name); } } else{ document.getElementById('name').focus(); } };
驗證成功後,對用戶輸入消息要觸發的事件:
$scope.sendMsg = function(data){ var date = new Date(); data = $scope.content; if($scope.content !== ''){ socket.emit('sendMsg',data); } $scope.content = ''; };
程式的部分運行測試結果:
瀏覽器輸入localhost後展示的用戶登錄界面:
昵稱重覆後的提示:
昵稱輸入成功後進入當前用戶的聊天界面:
源碼地址:github
參考學習:
Node.js + Web Socket 打造即時聊天程式嗨聊