nodejs where to start?

后端 未结 4 1339
臣服心动
臣服心动 2021-02-01 23:21

I\'ve installed nodejs and ran couple of simple examples like opening a server on a port and listen on that port.

However, I still can not relate nodejs to web develop

4条回答
  •  庸人自扰
    2021-02-01 23:48

    I'd recommend looking at the project Socket.IO and Socket.IO-node. It uses HTML5 WebSockets if available, and falls back automatically and gracefully (no intervention required) to Flash sockets and XHR-polling as necessary

    Here's a script to download the files:

    mkdir socket.io
    cd socket.io
    git clone https://github.com/LearnBoost/Socket.IO.git --recursive
    git clone https://github.com/LearnBoost/Socket.IO-node.git --recursive
    

    Here's the server.js file:

    var http=require('http');
    var url=require('url');
    var fs=require('fs');
    var sys=require('sys');
    var io=require('./socket.io/Socket.IO-node');   //adjust path as necessary...
    
    var server=http.createServer(function(req,res){
        res.writeHead(200,{'Content-Type':'text/html'});
        res.write('Hello world');
        res.end();
    });
    server.listen(8000);
    
    var socket=io.listen(server);
    
    socket.on('connection', function(client){
      onConnection(client);
      client.on('message', function(){
        onMessage();
      })
      client.on('disconnect', function(){
        onDisconnect();
      })
    });
    function onConnection(client){
      console.log('connection');
      //client.connected;   //tests if connected
      //client.send("message");
      //client.broadcast("message");   //send to all other conns
    }
    function onMessage(){
      console.log('message');
    }
    function onDisconnect(){
      console.log('disconnect');
    }
    
    });
    

    Run the above server with sudo node server.js

    And here is your index.html to be run in a browser:

       
    
    

提交回复
热议问题