nodejs+socket.io即时聊天实例

来源:互联网 发布:跑腿微信小程序源码 编辑:程序博客网 时间:2024/05/03 12:53
分类: NodeJs 2428人阅读 评论(1) 收藏 举报
即时聊天socket限时通迅

在这之前你应该先安装好 Node.js,安装过程不再讲解

首先在你的电脑上创建一个新目录,姑且命名为 chat,然后在该目录创建两个文件,分别是 app.js 和 index.html。

app.js

[html] view plaincopyprint?
  1. var fs = require('fs')  
  2.     , http = require('http')  
  3.     , socketio = require('socket.io');  
  4.    
  5. var server = http.createServer(function(req, res) {  
  6.     res.writeHead(200, { 'Content-type': 'text/html'});  
  7.     res.end(fs.readFileSync(__dirname + '/index.html'));  
  8. }).listen(8080, function() {  
  9.     console.log('Listening at: http://localhost:8080');  
  10. });  
  11.    
  12. socketio.listen(server).on('connection', function (socket) {  
  13.     socket.on('message', function (msg) {  
  14.         console.log('Message Received: ', msg);  
  15.         socket.broadcast.emit('message', msg);  
  16.     });  
  17. });  
安装 Socket.IO 了,可在命令行窗口进入当前文件目录中执行如下命令
[html] view plaincopyprint?
  1. npm install socket.io  
运行 app.js 服务
[html] view plaincopyprint?
  1. node app.js  
现在你可以打开两个浏览器,访问 http://127.0.0.1:8080/ 地址开始互聊了
0 0