Tigerrrrr
Tigerrrrr

Reputation: 1356

Socket.io | Type Error: socket.emit is not a function

I've seen many questions and none of them fix my problem.

Here's my JS (app.js) code:

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

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/client/index.html');
});

app.use('/client', express.static(__dirname + '/client'));

serv.listen(2000);
console.log('Server has started.');

var socket_list = {};

var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {

    console.log('Socket Connection');

    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket_list = socket.id = socket;

});

setInterval(function() {
    for(var i in socket_list) {
        var socket = socket_list[i];
        socket.x++;
        socket.y++;
        socket.emit('newPosition', {
            x: socket.x,
            y: socket.y
        });
    }
}, 1000/25);

Here is my HTML (index.html) code:

<!DOCTYPE html>
<html>
<head>
    <title>Multiplayer | HTML5</title>
  <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
  <canvas id="ctx" width="512" height="512" style="border: 1px solid #000;"></canvas>

  <script type="text/javascript">
    var ctx = document.getElementById('ctx').getContext('2d');
    ctx.font = '24px Calibri';

    var socket = io();

    socket.on('newPosition', function(data) {
        ctx.clearRect(0,0,500,500);
        ctx.fillText('P', data.x, data.y);
    })
  </script>
</body>
</html>

I'm following this tutorial: https://www.youtube.com/watch?v=_GioD4LpjMw&feature=youtu.be

It's 3 years old but everything is going smoothly until 4:47 in the video ^^.

Using the exact same code above ^^ I get this:

enter image description here

Upvotes: 0

Views: 2182

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12552

You are replacing Socket list object with a Socket object. Also use io.on.

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

    console.log('Socket Connection');

    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket_list = socket.id = socket;

});

You need to change it to,

io.on('connection', function(socket) {//use io.on

    console.log('Socket Connection');

    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket_list[socket.id] = socket;//fix this error

});

Change io.emit to socket.emit.

socket.emit('newPosition', {
    x: socket.x,
    y: socket.y
});

Upvotes: 1

Related Questions