简体   繁体   中英

getting simple node.js socket.io example working

i downloaded this very simple socket.io example from: https://github.com/shapeshed/nodejsbook.io.examples/tree/master/hour12/example02

package.json:

{       "name"          :       "socketio_example"
,       "version"       :       "0.0.1"
,       "private"       :       "true"
,       "dependencies"  :       {       "socket.io"     :       "0.8.7" }
}

app.js:

var http        = require('http')       ;
var fs          = require('fs')         ;
var count = 0;
var server = http.createServer(function (req, res)      {
    fs.readFile('./index.html'      ,   function(error, data)   {
            res.writeHead(200,      {   'Content-Type'  :       'text/html'});
            res.end(data, 'utf-8');
    });
}).listen(3000, "1xx.2xx.1xx.26");
console.log('Server is running');

var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
    count++;
    console.log('User connected; ' + count + ' user(s) present.' );
    socket.emit             ('users'     ,   {   number  :   count   })    ;
    socket.broadcast.emit   ('users'     ,   {   number  :   count   })    ;
    socket.on('disconnect', function()   {
            count--;
            console.log('User disconnected; ' + count + ' user(s) present.' );
            socket.broadcast.emit('users'   , {       number  :       count   })      ;
    });
});

index.html:

<!DOCTIME html>
<html lang='en'>
<head>
<title>Socket.IO Example</title>
</head>
<body>
<h1>Socket.IO Example</h1>
<p id='count'></p>
<script src='/socket.io/socket.io.js'></script>
<script>
    var socket = io.connect('http://1xx.2xx.1xx.26:3000')   ;
    var count = document.getElementById('count');
    socket.on('users', function(data)       {
            console.log('Got update from the server!');
            console.log('There are ' +  data.number + ' users!');
            count.innerHTML = data.number;
    });
<script>
</body>
<html>

and then did:

node  install  ;

and finally:

node app.js   &

then when i tried this using localhost (127.0.0.1), i can see my html code by doing:

curl http://127.0.0.1:3000 ;

then i changed the IP number from 127.0.0.1 to my own. and restarted the app. this command:

curl http://1xx.2xx.1xx.26:3000 ;

once again shows me the html code.

this project is supposed to display a count of the number of connections, but i cannot seem to get it working properly. however, i am not getting any errors either. the webpage is coming up when i browse to http://1xx.2xx.1xx.26:3000/ and the title appears but nothing else, no user count.

when a webpage connects i do this this message on the server:

 debug - served static content /socket.io.js

any suggestions or thoughts what i might be doing wrong?

thank you all!

I too was having a lot of trouble wrapping my head around some of the examples I was seeing out there of socket.io, so I tried to break it down as simply as I could. Maybe this may help you as well.

I adapted this example from the example posted here: http://socket.io/get-started/chat/

First, start in an empty directory, and create a very simple file called package.json Place the following in it.

{
"dependencies": {}
}

Next, on the command line, use npm to install the dependencies we need for this example

$ npm install --save express socket.io

This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

Create a file called server.js This will obviously be our server run by node. Place the following code into it:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

Create the last file called index.html and place the following code into it.

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

You can now test this very simple example and see some output similar to the following:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.

i installed a fresh linux on virtualbox and played with this. it worked fine running localhost but not over the net.

the answer was pretty obvious:

app.js -

original line 9&10:

}).listen(3000, "127.0.0.1");
console.log('Server running at http://127 .0.0.1:3000/');

new line 9&10:

}).listen(3000);
console.log('Server running at port 3000/');

index.html :

original line 13:

var socket = io.connect('http://127.0.0.1:3000');

new line 13:

var socket = io.connect('http://1xx.2xx.3xx.1:3000');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM