ÏȼÓÔØËùÐèÒªµÄͨÐÅÄ£¿é£º
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('http://www.cnblogs.com/',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);
Á¬½Ó³É¹¦ºó£¬¶ÔÓû§êdzÆÊäÈëµÄÑéÖ¤£º
$scope.checkName = function () { if($scope.name!==''){ if($scope.personlist.length!==0){ if($scope.personlist.indexOf($scope.name)>-1) { document.getElementById("info").textContent = "¸ÃêdzÆÒѱ»Õ¼Óã¬ÇëÖØÐÂÊäÈë"; } 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ºóչʾµÄÓû§µÇ¼½çÃæ:
êdzÆÖظ´ºóµÄÌáʾ£º
êdzÆÊäÈë³É¹¦ºó½øÈ뵱ǰÓû§µÄÁÄÌì½çÃ棺
Ô´ÂëµØÖ·£ºgithub
²Î¿¼Ñ§Ï°£ºNode.js + Web Socket ´òÔ켴ʱÁÄÌì³ÌÐòàËÁÄ
»ùÓÚwebsocketµÄÒ»¸ö¼òµ¥µÄÁÄÌìÊÒ
¡¡