PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] Why am I not receiving a console.log that a new socket user has connected?

 October 22, 2022     express, javascript, node.js, sockets     No comments   

Issue

I'm more or less following the socket.io documentation and trying to apply it to my slightly different project but I believe I'm making some mistake. I've used express-generator to create my project's skeleton and therefore I got app.js file, www file and route files.

I've put this code in www file:

var io = require('socket.io')(http);
console.log('Socket is running!');
io.on('connection', function(socket){
    console.log('A User Has Connected: ' + socket.id);
});

This code in my footer file:

<script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-3.2.1.min.js"></script>
<script src="/javascripts/javascript.js"></script>
</body>
</html>

And this in my JavaScript file:

$(document).ready(function(){

    var socket = io();

});

Now I understand that when a request is made, the console should log "A User Has Connected: " + the id of the socket but I'm not getting anything other than "Socket is running!". I assume I'm missing something but can't figure it out and the documentation is using the same code.

var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

Solution

You have to use the same server instance express-generator creates, which is the following line in www file

var server = http.createServer(app);

To use that, change

var io = require('socket.io')(http);

to

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


Answered By - Brahma Dev
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing