zoukankan      html  css  js  c++  java
  • 修改上一篇文章的node.js代码,支持默认页及支持中文

    服务端 app.js

    var app = require('http').createServer(handler)
    var io = require('socket.io')(app);
    var fs = require('fs');
    var url = require("url");
    
    app.listen(80);
    
    function handler (req, res) {
      var pathname = url.parse(req.url).pathname;
      if(pathname == "/") {
        pathname = "/index.html";
      }
      fs.readFile(__dirname + pathname, 'utf-8',
      function (err, data) {
        if (err) {
          res.writeHead(500);
          return res.end('Error loading ' + pathname);
        }
    
        res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
        res.end(data);
      });
    }
    
    io.on('connection', function (socket) {
      socket.emit('news', { hello: 'world' });
      socket.on('my other event', function (data) {
        console.log(data);
      });
    
      socket.on('disconnect', function (data) {
        console.log('disconnect:' + data);
      });
    });

    说明:

    1、如果没有指定默认页,默认加载/index.html页面

    2、主要是通过这句话来支持中文 res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});

    客户端 index.html

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>demo</title>
    </head>
    
    <body>
    <script src="/socket.io/socket.io.js"></script>
    <script src="jquery-2.1.1.js"></script>
    <script>
      var socket = io('http://localhost');
      socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
      });
    
    $(document).ready(function(){
      alert("页面加载完成!");
    }); 
    </script>
    </body>
    </html>
  • 相关阅读:
    Convert MSTest to Nunit
    ASP.NET MVC RenderPartial to String
    RailsCasts批量下载地址之Ruby代码
    合并CSS和JavaScript(转载)
    删除Windows Service
    WCF和IIS宿主的ASP.NET 共享会话
    远程桌面常用快捷键
    ColdFusion 9 Installation on IIS7
    Ruby正则表达式实践非贪婪量词
    发布时和调试时使用不同的JS
  • 原文地址:https://www.cnblogs.com/modou/p/6266863.html
Copyright © 2011-2022 走看看