如何使用套接字IO在Python客户端和NodeJS服务器之间进行通信?

时间:2018-06-13 08:52:11

标签: javascript python node.js socket.io

我正在尝试使用Socket IO在NodeJS服务器和Python客户端进程之间进行通信。要开始,我想将输入消息从Python进程发送到NodeJs Process,它可以在console.log中显示消息。

我在https://pypi.org/project/socketIO-client/中跟踪了示例代码。

在我的app.js(nodejs文件)中:

var express        = require("express");
var app            = express();
var server         = require("http").Server(app);
var io             = require('socket.io')(server);
server.listen(3000,()=>{
    console.log("Succesful");
});
io.on('connection',function(socket){
    //data is the message I wish to receive from python
    socket.on('news',(data)=>{  
    console.log(data);
    });
});

在python脚本中(在输入数据后死亡):

from socketIO_client import SocketIO,LoggingNamespace
import logging

while True:
    data = input("Enter your test data here:")
    with SocketIO('localhost', 3000, LoggingNamespace) as socketIO:
        socketIO.emit('news',{data : data})
        socketIO.wait(seconds=1)

问题: 当我尝试执行我的python代码时,输​​入我的数据后出现此错误

File "/home/anhtumai/.local/lib/python2.7/site- 
packages/socketIO_client/__init__.py", line 353, in __init__
resource, hurry_interval_in_seconds, **kw)
File "/home/anhtumai/.local/lib/python2.7/site- 
packages/socketIO_client/__init__.py", line 54, in __init__
self._transport
File "/home/anhtumai/.local/lib/python2.7/site- 
packages/socketIO_client/__init__.py", line 62, in _transport
self._engineIO_session = self._get_engineIO_session()
File "/home/anhtumai/.local/lib/python2.7/site- 
packages/socketIO_client/__init__.py", line 76, in 
_get_engineIO_session
transport.recv_packet())
StopIteration'

我需要在脚本中修改什么(NodeJS和Python)?

1 个答案:

答案 0 :(得分:1)

现在我发现了问题所在。这个库https://pypi.org/project/socketIO-client/。不再与socketIO 2.0兼容。为了使其有效,我只需使用https://pypi.org/project/socketIO-client-nexus/。它们的用法基本相同。我只是使用socketIO_client_nexus从socketIO_client进行更改,它就像魅力一样。

相关问题