诚然博客

  • 首页
  • HTML
  • Jquery
  • PHP
  • ThinkPHP
  • Linux
  • 琐事
  1. 首页
  2. Nodejs
  3. 正文

弄nodejs的一些记录

2015年3月19日 2266点热度

安装 淘宝镜像 npm install express --registry=https://registry.npm.taobao.org

var app = require('http').createServer(handler),
io = require('socket.io').listen(app), fs = require('fs')app.listen(8080);
io.set('log level', 1);//将socket.io中的debug信息关闭
function handler (req, res) {
    fs.readFile(__dirname + '/index.html',function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        }
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        });
    }

        io.sockets.on('connection', function (socket) {
        socket.emit('news', { hello: 'world' });
        socket.on('my other event', function (data) {
        console.log(data);
    });
});

客户端

<script type="text/javascript" src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript"> 
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) { 
alert(data.hello);
socket.emit('my other event', { my: 'data' });
}); 
</script>

标签: 暂无
最后更新:2016年2月26日

诚然

这个人很懒,什么都没留下

点赞
< 上一篇

COPYRIGHT © 2012-现在 诚然博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

鄂ICP备2022012104号