需要安装的模块 文件清单 index.js index.html 启动 使用 需要安装的模块 npm install socket.io npm install express 文件清单 index.js index.html index.js //加载需要的模块 var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); //存储Socket的数组对象 var socketsArray = new Array(); //定义/im路径返回index.html页面 app.get('/im', function(req,res){ res.sendFile(__dirname+'/index.html'); }); io.on('connection', function(socket){ socketsArray.push(socket); //断开连接的时候将socket连接Pop出数组 socket.on('disconnect',function(){ socketsArray.pop(socket); }); //当接收到消息时的操作 socket.on('sendMsg', function(msg){ console.log('message: ' + msg); for (i=0;i<socketsArray.length;i++) { socketsArray[i].emit('data', msg ); } }); }); http.listen(3000, function(){ console.log("listenning on * : 3000"); }); index.html <!doctype html> <html> <head> <title>Socket.IO chat</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css"> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap-theme.min.css"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="http://cdn.bootcss.com/html5shiv/3.7.0/html5shiv.min.js"></script> <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container" style="margin-top: 20px;"> <form action="" role="form"> <textarea id="m" class="form-control"></textarea> <button class="btn btn-primary" style="margin-top:10px;">Send</button> </form> <div id="messages" class="jumbotron" style="margin-top:10px;"> <!--<p class="alert alert-success">Test</p>--> </div> </div> </body> <script src="/socket.io/socket.io.js"></script> <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script> <script src="http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script> var socket = io.connect('http://localhost:3000'); $('form').submit(function(){ socket.emit('sendMsg', $('#m').val()); $('#m').val(''); return false; }); socket.on('data', function(data){ $('#messages').html($('#messages').html() + new Date()+ '<p class="alert alert-success">'+ data + '</p>'); }) </script> </html> 启动 node index.js 使用 打开2个不同的浏览器,或者同浏览器不同的Session。在浏览器中输入http://localhost:3000/im 当信息提交之后