将网络套接字消息从Python客户端发送到NodeJS服务器

时间:2018-08-01 09:32:00

标签: python node.js sockets

首先,感谢您提供的任何帮助。我正在尝试使用python(3.7)连接并将消息发送到NodeJS(v8.11.3)服务器(由其他人编写)。即使我可以连接并(似乎)从python脚本发送消息,NodeJS服务器也没有任何响应(尽管它意味着只要有客户端连接或收到消息就打印消息)。如果创建python服务器,我的python代码将运行;如果使用NodeJS客户端,则NodeJS服务器将运行。我准备重写代码,但我想我先在这里问一下。

这是我用来解决问题的简单Python客户端脚本:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
local_hostname = socket.gethostname()
local_fqdn = socket.getfqdn()
ip_address = socket.gethostbyname(local_hostname)

server_address = (ip_address, 20001)
sock.connect(server_address)

sock.sendall(str("Hello World").encode("utf-8"))

这是我要连接的NodeJS服务器的start.js:

'use struct';

const MessageForward = require('./MessageForward');

//Controller Python: use port 20001
wsControllerPython = new MessageForward();
wsControllerPython.messageEventListener.on(MessageForward.EVENT_MESSAGE
_RECEIVED, forward_ControllerPythonToUnity);
wsControllerPython.start(20001, 'ControllerPython');

function forward_ControllerPythonToUnity(messageToForward)
{
    wsControllerUnity.forwardMessage(messageToForward);
}

和MessageForward.js:

'use struct';

//=======================================================================
const DateTime = require('node-datetime');
var http = require('http');
//var url = require('url');
var WebSocketServer = require('websocket').server;
const Events = require('events');

const MessageForward_EVENT_MESSAGE_RECEIVED = 
'MessageForward_EVENT_MESSAGE_RECEIVED';


class MessageForward
{
    //const string of the class
    static get EVENT_MESSAGE_RECEIVED()
    {
        return MessageForward_EVENT_MESSAGE_RECEIVED;
    }

    constructor()
    {
        //Setup default variables
        this.clients = [];
        this.messageEventListener = new Events.EventEmitter();
    }

    //Called by start.js
    start(port, theServerName) {
        this.serverName = theServerName;
        this.port = port;

        function onRequest(request, response) {
            console.log(DateTime.create().format('Y-m-d H:M:S') + ' >> 
Request for websocket http server received.');
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write("RUNNING (websocket [" + this.serverName + "]");
            response.end();
        }


//==========================================================================
        var server = http.createServer(onRequest).listen(port, function() {
            console.log(DateTime.create().format('Y-m-d H:M:S') + ' >> Web 
Socket Server [' + this.owner.serverName + '] has started on port ' + port);
        });
        server.owner = this;    //make the owner pointer for getting class 
variable from another class function callback


//==========================================================================
        this.wsServer = new WebSocketServer({
            httpServer: server
        });
        this.wsServer.owner = this;    //make the owner pointer for getting 
class variable from another class function callback


//==========================================================================
        //Called by connection when receive any message
        function onWsConnMessage(message) {
            if (message.type == 'utf8') {
                console.log(DateTime.create().format('Y-m-d H:M:S') + ' >> WS 
[' + this.owner.serverName + '] Received message: ' + message.utf8Data);

this.owner.messageEventListener.emit(MessageForward.EVENT_MESSAGE_RECEIVED, 
message.utf8Data);  //dispatch event (forward whole message)
            } else if (message.type == 'binary') {
                console.log(DateTime.create().format('Y-m-d H:M:S') + ' >> WS 
[' + this.owner.serverName + '] Received binary data.');
            }
        }

        //Called by connection when close
        function onWsConnClose(reasonCode, description) {
            console.log(DateTime.create().format('Y-m-d H:M:S') + ' >> WS 
Peer disconnected with reason: ' + reasonCode);
        }


//==========================================================================
        //Called by WSServer 
        function onWsRequest(request) {
            try
            {
               // var connection = request.accept('forward- 
//message',request.origin);
                var connection = request.accept();
                console.log(DateTime.create().format('Y-m-d H:M:S') + ' >> WS 
WebSocket connection accepted.');
                connection.on('message', onWsConnMessage);
                connection.on('close', onWsConnClose);
                connection.owner = this.owner;    //make the owner pointer 
for getting class variable from another class function callback

                this.owner.clients.push(connection);
            } catch (ex)
            {
                console.log(DateTime.create().format('Y-m-d H:M:S') + ' Error 
occurs in onWsRequest');
                console.log(ex);
            }
        }

        this.wsServer.on('request', onWsRequest);
    }


//========================================================================
    //Called by start.js
    forwardMessage(utfMessage)
    {
        console.log(DateTime.create().format('Y-m-d H:M:S') + ' >> 
forwardMessage(' + utfMessage + ') is called');

        this.clients.forEach(function(client) {
            client.send(utfMessage);
        });
    }
}

module.exports = MessageForward;    //export the class

我意识到通读很多代码,为此我深表歉意。只是我无法弄清楚为什么没有任何响应(或错误),并希望你们能提供尽可能多的细节,以防万一我错过了什么。只要使用pip和npm安装依赖项,您就应该能够复制脚本并对其进行测试。

0 个答案:

没有答案