socket.io - ReferenceError: socket is not defined

丶灬走出姿态 提交于 2020-01-03 15:55:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17604767/socket-io-referenceerror-socket-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!