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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With