首页 > 解决方案 > 尝试为 Node.JS 客户端编写 python 服务器,无法获取数据

问题描述

我最近一直在玩一些 js 和 python,并想构建一个基本的服务器客户端应用程序,但在从客户端接收数据时遇到了麻烦。

client.js

const _ = require('underscore');
const async = require('async');
const net = require('net');
const readline = require('readline');

module.exports = class Client {
  constructor(port) {
    this._port = port;
  }

  run(commands, done) {
    function reject(msg) {
      s.destroy();
      done(msg);
    }

    done = _.once(done);

    var s = net.connect({port: this._port}),
        rl = readline.createInterface({input: s}),
        handshaked = false,
        output = [];

    s.on('error', done);

    rl.on('line', line => {
      if (handshaked) {
        output.push(line);

        return;
      }

      handshaked = true;

      if (line !== 'hello')
        return reject('Expected: hello');

      s.write(commands.map(c => c + '\r\n').join('  '));
      s.write('quit\r\n');
    });

    rl.on('close', () => done(null, output));

    setTimeout(() => done('timeout'), 1000);
  }
}

server.py

import socket
import sys


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = ('localhost', 8124)
sock.bind(server_address)

sock.listen(1)

while True:
    # Wait for a connection
    print(sys.stderr, 'waiting for a connection')

    connection, client_address = sock.accept()
    try:
        print(sys.stderr, 'connection from {} ', client_address)

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(1024)
            if data:
                print(sys.stderr, 'sending data back to the client')
                connection.sendall(data)
            else:
                print(sys.stderr, 'no more data from {} ', client_address)
                break
            
    finally:
        # Clean up the connection
        connection.close()

我正在尝试打印数据,但得到的是空字符串。服务器连接到客户端,但不打印它接收到的任何数据。

标签: pythonnode.jssocketswebsocket

解决方案


推荐阅读