socket.io-ReferenceError:未定义套接字 [英] socket.io - ReferenceError: socket is not defined

查看:133
本文介绍了socket.io-ReferenceError:未定义套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的应用程序,以将我在文本区域中键入的每个字符镜像到 div使用socket.io,但我不断收到以下客户端错误:"ReferenceError:未定义套接字"

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"

这是我的服务器代码:

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); 
    });


});

客户代码:

    <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?

推荐答案

嗯,这不是很明显吗?您尚未在客户端代码中定义socket(这就是ReferenceError的意思):

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
});

请注意,iosocket.io.js脚本中的全局变量.

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

这篇关于socket.io-ReferenceError:未定义套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆