duanjuan3931 2016-11-12 05:32 采纳率: 0%
浏览 158

Socket.io js没有连接

I have a node.js server running on the port 8443. Whenever I try to run the application through the browser my socket.io keeps connecting for about 20 seconds before the url turns red at the end.

Edit 3 : This is my directory structure and now with updated files

/var/www/html/nodetest/

Inside this

/node_modules
/app.js
/index.html

Node JS is installed on server.

Here is my main app.js code (as suggested in answer) :

 var app = require('express')();
 var server = require('http').createServer(app);
 var io = require('socket.io')(server);
 var fs = require('fs');

  // Run server to listen on port 8443.
  server = app.listen(8443, () => {
   console.log('listening on *:8443');
 });

 io.listen(server);

 io.sockets.on('connection', function(socket) {
   socket.emit('message', 'this is the message emitted by server');
  });   

 app.get('/', function(req, res){
   fs.readFile(__dirname + 'index.html', function(error, data) {
      res.writeHead(200);
      res.end(data);         
   });
 });

And this is my client browser side code:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.5.1    
 /socket.io.min.js"></script>
   <script type="text/javascript">
       var websocket;
        function onload() {
        websocket = io.connect();
        websocket.on('message',function(data) {
           console.log('Received a message from the server!',data);
        });

     };
   </script>
 </head>
 <body onload="onload()">
    <div id="divId"></div>
 </body>
 </html>

Here is an image of the error

enter image description here

Now it shows 404 Error

  • 写回答

1条回答 默认 最新

  • duanji1902 2016-11-13 01:53
    关注

    You are creating two separate servers and only starting one of them so your socket.io server is never started.

    Change this:

      var app = require('express')();
      var server = require('http').createServer(app);
      var io = require('socket.io')(server);
    
      // Run server to listen on port 8000.
      server = app.listen(8447, () => {
       console.log('listening on *:8447');
      });
    

    to this:

      var app = require('express')();
    
      // Run server to listen on port 8000.
      var server = app.listen(8447, () => {
       console.log('listening on *:8447');
      });
      var io = require('socket.io')(server);
    

    app.listen() creates its own server so you don't want to use both it and http.createServer().

    Here's the code for app.listen() so you can see how it works:

    app.listen = function(){
      var server = http.createServer(this);
      return server.listen.apply(server, arguments);
    };
    

    So, you can see that the server you created with http.createServer() and then bound to socket.io was never started with .listen().

    评论

报告相同问题?