【问题标题】:ReferenceError: socket is not definedReferenceError:未定义套接字
【发布时间】:2016-03-22 15:30:41
【问题描述】:

我有一个 python 脚本,每次恢复一个新值时都会向我的 node.js 服务器发送数据。

这是我的代码客户端(python 脚本):

from socketIO_client import SocketIO

...

def update_db(dateUpdate, res, nameIndex):
    try:
        with SocketIO('192.168.100.103', 8080) as socketIO:
             socketIO.emit('newValues', res)

    except Exception as e:
        print "error socketIO - Impossible to emit data \n"

    #Update database

while True:
    #If new value
        dateUpdate = time.strftime('%Y-%m-%d %H:%M:%S')
        update_db(dateUpdate, res, nameIndex[i])
        break

这是我的 node.js 服务器:

var path = require('path');
var fs = require('fs');
var mysql = require("mysql");
var express = require('express');

var app = express();

var server = app.listen(8080);
console.log('Server listening on port 8080');

var io = require('socket.io')(server);

io.sockets.on('connection', function () {
    console.log("client connected");

    socket.on('newValues', function (data) {
            console.log("new values : "+data);      
    });
});

问题:

每次我的 python 脚本收到新数据并且必须发出一条消息。我的节点服务器停止并显示此错误:

node server.js

Server listening on port 8080
client connected
C:\project\src\server\server.js:26

socket.on('newValues', function (data) {
    ^

ReferenceError: socket is not defined
    at Namespace.<anonymous> (C:\project\src\server\server.js:26:5)
    at emitOne (events.js:90:13)
    at Namespace.emit (events.js:182:7)
    at Namespace.emit (C:project\node_modules\socket.io\lib\nam
espace.js:206:10)
    at C:\project\node_modules\socket.io\lib\namespace.js:174:14

    at nextTickCallbackWith0Args (node.js:452:9)
    at process._tickCallback (node.js:381:13)

有人知道错误吗?

【问题讨论】:

    标签: python node.js python-2.7 socket.io


    【解决方案1】:

    未定义套接字。您需要将套接字传递给您的 io.sockets.on 回调函数。

    io.sockets.on('connection', function (socket) {    //Pass socket here
        console.log("client connected");
    
        socket.on('newValues', function (data) {
            console.log("new values : "+data);      
        });
    }
    

    编辑:这是我乍一看最好的猜测解决方案。我对sockets.io不是很有经验。我只是在看文档(这个链接有一个类似的例子)http://socket.io/docs/

    【讨论】:

    • 评论“Pass socket here”帮了大忙!
    【解决方案2】:

    当你写作时

    socket.on( 'newValues' , ...)
    

    假设“socket”是一个变量。如果是,则在该调用之前尚未定义。

    我不太了解 IO,但可以试试这个:

    io.sockets.on( 'newValues' , ...)
    

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 2013-07-10
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2015-10-04
      • 2017-04-10
      相关资源
      最近更新 更多