node.js 用socket实现聊天的示例代码
本文介绍了node.js用socket实现聊天的示例代码,分享给大家,也给自己留个笔记,具体如下:
服务器搭建
app.js
consthttp=require("http");
constexpress=require("./express");
//创建一个服务
constserver=http.createServer(express);
//监听服务端口
server.listen(8001,()=>{
console.log("服务端已经启动,请访问http://localhost:8001");
});
express.js
consturl=require("url");
constfs=require("fs");
functionexpress(req,res){
varurlObj=url.parse(req.url);
//console.log(urlObj);
varfilePath="./www"+urlObj.pathname;
varcontent="notfound";
if(fs.existsSync(filePath)){
content=fs.readFileSync(filePath);
}
res.end(content.toString());
}
module.exports=express;
index.html
Socket.IOchat