Project FH Project FH - 6 months ago 36
jQuery Question

Socket.io : "Cannot read property 'emit' of undefined"

So I'm currently developping my website using socket.io.

Today, while I was implementing the sockets, I got a nice little error "Cannot read property 'emit' of undefined"
I can not find what's wrong in my code so I hope you guys can help me.

App.js:

var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = 9999;

server.listen(port, function () {
console.log('Listening at port %d', port);
});

io.sockets.on('connection', function (socket) {
console.log('User connected');

socket.on('create_socket', function(port){
console.log(port);
});


Client Side:

<div>
<p class="connected" hidden>Connected port : 9999</p>
<p class="connect_error" hidden><strong>Can not connect to socket on port 9999</strong></p>
</div>

<script>
var socket = io.connect("http://localhost:9999");

// If connection can not be established
socket.on('connect_error', function(socket) {
$('.connected').hide();
$('.connect_error').show();
});

// Connection established
socket.on('connect', function(socket) {
$('.connect_error').hide();
$('.connected').show();
// socket.on('create_socket', null, <?= $port; ?> );
socket.emit('create_socket', '<?= $port; ?>');
});
</script>


Btw, all the socket.io/jquery/... includes are done correctly even if they doesn't appear on the code

Thanks in advance

Answer

Client Code:

Change

// Connection established
    socket.on('connect', function(socket) {

to

// Connection established
    socket.on('connect', function(data) {

final:

// Connection established
    socket.on('connect', function(data) {
        $('.connect_error').hide();
        $('.connected').show();
       console.log(data);
       socket.emit('create_socket', '<?= $port; ?>');
    });

Previously, you where overwriting the socket object.