首页 / 操作系统 / Linux / Node.js+Socket.IO即时聊天实例
在这之前你应该先安装好 Node.js,安装过程不再讲解。首先在你的电脑上创建一个新目录,就暂且命名为 chat,然后在该目录创建两个文件,分别是 app.js 和 index.html。app.jsvar fs = require("fs")
, http = require("http")
, socketio = require("socket.io");
var server = http.createServer(function(req, res) {
res.writeHead(200, { "Content-type": "text/html"});
res.end(fs.readFileSync(__dirname + "/index.html"));
}).listen(8080, function() {
console.log("Listening at: http://localhost:8080");
});
socketio.listen(server).on("connection", function (socket) {
socket.on("message", function (msg) {
console.log("Message Received: ", msg);
socket.broadcast.emit("message", msg);
});
});安装 Socket.IO 了,可在命令行窗口进入当前文件目录中执行如下命令npm install socket.io运行 app.js 服务node app.js现在你可以打开两个浏览器,访问 http://127.0.0.1:8080/ 地址开始互聊了。相关阅读:Node.js+socket.io+聊天室源码 http://www.linuxidc.com/Linux/2013-10/91617.htmNode.js 的详细介绍:请点这里
Node.js 的下载地址:请点这里推荐阅读:Node.Js入门[PDF+相关代码] http://www.linuxidc.com/Linux/2013-06/85462.htmNode.js安装与配置 http://www.linuxidc.com/Linux/2013-05/84836.htmSocket.IO 和 Node.js 入门 http://www.linuxidc.com/Linux/2012-05/60447.htm使用HTML5,WebSockets,nodejs和socket.io构建实时游戏 http://www.linuxidc.com/Linux/2012-06/61798.htm