本文介绍了node.js 用socket实现聊天的示例代码,分享给大家,也给自己留个笔记,具体如下:
服务器搭建
app.js
//创建一个服务
const server = http.createServer(express);
const server = http.createServer(express);
//监听服务端口
server.listen(8001,()=>{
console.log("服务端已经启动,请访问 http://localhost:8001");
});
express.js
function express(req,res){
var urlObj=url.parse(req.url);
//console.log(urlObj);
var urlObj=url.parse(req.url);
//console.log(urlObj);
var filePath="./www"+urlObj.pathname;
var content="not found";
if(fs.existsSync(filePath)){
content=fs.readFileSync(filePath);
}
res.end(content.toString());
}
module.exports=express;
index.html
<Meta charset="utf-8"/>
Socket.IO chat
<script src="js/lib/jquery-1.11.1.js"></script>
<script src="js/lib/socket.io.js"></script>
<script src="js/index.js"></script>