Node.js and socket.io don't work on Cloud9 IDE

六月ゝ 毕业季﹏ 提交于 2019-12-05 08:25:47

1. Steps

1.1) Run server.js

The cloud 9 console shows up:

1.2) Hit Preview on index.html

1.3) Then a window is opening on the right side of your IDE. You can either hit the button in the middle of the navigation bar or copy and paste the url into a new browser window.

1.4) Socket communication is working!



2. Prerequisite

2.1) node module socket.io

Hit F6 or View -> Console and install socket.io.

2.2) the client side JavaScript from socket.io

Since I didn't find an official link to download it, I created a GitHubGist.

socket.io.js



3. Code

server.js

// module dependencies
var http = require("http"),
    sio  = require("socket.io");

// create http server
var server = http.createServer().listen(process.env.PORT, process.env.IP),

// create socket server
io = sio.listen(server);

// set socket.io debugging
io.set('log level', 1);

io.sockets.on('connection', function (socket) {

  socket.emit('news', { message: 'Hello world!' });

  socket.on('my other event', function (data) {
    console.log(data.message);
  });

});


index.html

<!DOCTYPE html>
<html>

        <script src="js/socket.io.js"></script>
        <script>

        var socket = io.connect("https://demo-project-c9-matthiasholdorf.c9.io");

        socket.on("news", function(data) {
            console.log(data.message);
        });

        socket.emit("my other event", { message : "client emit" } );

        </script>

</html>

Thanks for feedback from damphat and Matthias. After many failed attempts, finally I figured out the solution myself. On Cloud9 IDE, the typical line in client (test.html here) has to be changed from,

 <script src="/socket.io/socket.io.js"></script>

to

 <script src="https://webapp-c9-etlolap.c9.io/socket.io/socket.io.js"></script>

The prefix is the URL of your Cloud9 project URL. By changing this line, my example worked.

you must flowing these step:

open the terminal on https://c9.io/etlolap/webapp, type:

npm install socket.io
node test

then open a new tab of browser with url

https://webapp-c9-etlolap.c9.io/socket.io/socket.io.js

You will see socket.io.js source code


I did not how you open test.html in c9.io without http server, did you just press preview?


Edit:

To return html files, you should merge http server and socket.io server like this:

// file: test.js
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen( Number( process.env.PORT ) );

function handler (req, res) {
  fs.readFile(__dirname + '/test.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

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

To fetch any html file requested, using html files located in the file folder, you can use express:

var fs = require('fs');

var express = require('express');
var app = express();

// This fetches html files from the client folder (if they exist), and returns a "Page could not be found" error otherwise (this can be customized to some other 404 error page as desired)
app.get('*', function (req, res) {

    var urlReading = req.url;
    if (urlReading == "/")
    {
        urlReading = "/index.html";
    }
    urlReading = __dirname + "/client" + urlReading;

    console.log("Loading: " + urlReading);

    fs.readFile(urlReading, function (err, html) {
        if (err) {
            console.log("Could not find " + urlReading)
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end("<html><head><title>Page could not be found</title></head><body><h1>Page could not be found</h1></body></html>");
        }
        else
        {
            console.log("Found " + urlReading)
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(html);
        }

    });
});


app.listen(process.env.PORT, process.env.IP);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!