zoukankan      html  css  js  c++  java
  • Nodejs-- web服务器

    第一篇关于nodejs的东西,代码在此作为备份。

    该代码目前未完成,是一个阻塞式的代码。

    1.index.js

    ar server=require('./server');
    var route=require('./router');
    var requestHandler=require('./requestHandlers');
    
    <!-- 声明一个对象  -->
    var handle={}
    handle['/']=requestHandler.start;
    handle['/start']=requestHandler.start;
    handle['/upload']=requestHandler.upload;
    
    server.start(route.route,handle);

    2.server.js

    var http=require('http');
    var url=require('url');
    
    function start(route,handle){
            function onRequest(request,response){
                    var pathname=url.parse(request.url).pathname;
                    console.log('received pathname:'+pathname);
    
                    route(handle,pathname);
    
                    response.writeHead(200,{'Content-Type':'text/plain'});
                    response.write('hello world');
                    response.end();
            }
            http.createServer(onRequest).listen(8888);
            console.log('server has started');
    
    }
    
    exports.start=start;

    3.route.js

    function route(handle,pathname){
            console.log('About to route a request for '+pathname);
            if(typeof handle[pathname] == 'function'){
                    handle[pathname]();
            }else{
                    console.log('No request handler found for:'+pathname);
            }
    
    }
    
    exports.route=route;

    4.requestHandlers.js

    function start(){
            console.log('Request handler START was called');
            function sleep(millsec){
                    var startTime=new Date().getTime();
                    while(new Date().getTime()<startTime+millsec);
            }
            sleep(10000);
            return 'Hello Start';
    }
    
    function upload(){
            console.log('Request handler UPLOAD was called');
            return 'Hello Upload';
    }
    
    exports.start=start;
    exports.upload=upload;
  • 相关阅读:
    引号的区别
    QT中加载动态链接库
    QString 转换为 char *
    C++虚继承初识
    虚析构函数详解
    赋值兼容规则
    利用docker搭建spark hadoop workbench
    《用Java写一个通用的服务器程序》03 处理新socket
    《用Java写一个通用的服务器程序》02 监听器
    《用Java写一个通用的服务器程序》01 综述
  • 原文地址:https://www.cnblogs.com/juepei/p/4206408.html
Copyright © 2011-2022 走看看