Socket.IO 使用示例

jopen 12年前

socket.io(官网:http://socket.io/)是一个跨平台,多种连接方式自动切换,做即时通讯方面的开发很方便,而且能和 expressjs提供的传统请求方式很好的结合,即可以在同一个域名,同一个端口提供两种连接方式:request/response, websocket(flashsocket,ajax…).
下面是网摘的一个简单的聊天室代码。

server.js:

var express =  require('express'),      app = express.createServer(),      io = require('socket.io').listen(app),      fs = require('fs'),      mime = require('mime');    app.listen(8001);  app.get('/',function(req,res){      var realpath = __dirname + '/client.html';      //console.log(realpath);      res.writeHead(200,{'Content-Type':mime.lookup(realpath)});      res.end(fs.readFileSync(realpath));  });  app.get('/jquery.min.js',function(req,res){      var realpath = __dirname + '/jquery.min.js';      //console.log(realpath);      res.writeHead(200,{'Content-Type':mime.lookup(realpath)});      res.end(fs.readFileSync(realpath));  });  var getCurrTime = function(){      var d  = new Date();      return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();  };  io.sockets.on('connection', function (socket) {    socket.on('msg', function(msg){       var data = {username:socket.name,time:getCurrTime(),msg:msg};       socket.emit('msg',data);       socket.broadcast.emit('msg',data);    });    socket.on('login', function(username){       socket.name = username;       var data = {username:'SYSTEM',time:getCurrTime(),msg:'welcome '+socket.name+' in...'};       socket.broadcast.emit('msg',data);       socket.emit('msg',data);    });    socket.on('logout', function(username){       var data = {username:'SYSTEM',time:getCurrTime(),msg:'bye, '+socket.name+' leave...'};       socket.broadcast.emit('msg',data);       socket.emit('msg',data);    });    socket.on('disconnect', function () {          socket.send(getCurrTime()+' '+socket.name+ " out...");    });  });client.html: <script type="text/javascript" src="/jquery.min.js"></script>  <script type="text/javascript" src="/socket.io/socket.io.js"></script>  <script>  var url = window.location.protocol+'//'+window.location.host;  //alert(url);  var socket = io.connect(url);  socket.on('msg', function (data) {  showMsg(data);  });  var showMsg = function (data){};  $(function(){  showMsg = function(data){  var time = $('<span style="color:red;"></span>').html(data.time+'&nbsp;&nbsp;');  var username = $('<span style="color:blue;"></span>').html(data.username+'&nbsp;&nbsp;');  var say = $('<span style="color:black;"></span>').html('say:&nbsp;&nbsp;');  var msg = $('<span style="color:green;"></span>').text(data.msg);  var div = $('<div style="display:none;"></div>').append(time).append(username).append(say).append(msg);  div.insertAfter('#demo span:eq(0)').slideDown();//fadeIn();  //div.appendTo('#demo').fadeIn();  };  $('#butt_login').click(function(){  socket.emit('login',$('#username').val());  });  $('#butt_logout').click(function(){  socket.emit('logout',$('#username').val());  });  $('#butt_send').click(function(){  socket.emit('msg',$('#message').val());  });  });    </script>  Name: <input type="text" id='username' value=""/>  <input type="button" value="join" id="butt_login"/>  <input type="button" value="leave" id="butt_logout"/>  <br>  message: <input type="text" id='message' value=""/>  <input type="button" value="send" id="butt_send"/>  <div id='demo' style="boder:1px;border-style:dotted;width:800px;height:300px;overflow:auto;">  <span>...</span>  </div>  Tips: 1.确认tmp/foo/路径下已有jquery.min.js,如果没有,需要创建一个该文件;  2.确认已安装mime,安装方法:# npm install mime;  3.由于socket.io.js文件中会要求flash player版本》10.0;请确保此项要求满足。  Demo运行方法:# node server.js     开启浏览器输入localhost:8001(端口号可在server.js里配置),即可看到运行效果。