Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io - ReferenceError: socket is not defined

I'm trying to write a simple app that mirrors each character I type in a text area onto a div using socket.io, but I keep getting the following client error: "ReferenceError: socket is not defined"

Here's my server code:

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

server.listen(3000);

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

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

    socket.on('keyup', function(data){
        io.sockets.emit('keydisplay',data); 
    });


});

Client code:

    <div id="output"></div>
    <textarea id = "input"></textarea>

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>

    <script>
        jQuery(function($){

            $('#input').keyup(function(){
                content = $('#input').val();
                socket.emit('keyup', content);

            });

            socket.on('keydisplay', function(data){
                $('#output').append(data);
            }); 
        });


    </script>

Any leads? What am I doing wrong?

like image 701
Eugene Avatar asked Jul 11 '13 22:07

Eugene


1 Answers

Well, isn't that obvious? You haven't defined socket in your client code (that's what ReferenceError means):

jQuery(function($){
    var socket = io.connect('http://localhost');
    // the other code goes here
});

Note that io is a global variable in socket.io.js script.

like image 62
freakish Avatar answered Nov 18 '22 07:11

freakish