python - 尝试为 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()
我正在尝试打印数据,但得到的是空字符串。服务器连接到客户端,但不打印它接收到的任何数据。
解决方案
推荐阅读
- asp.net-mvc-4 - 索引数据库循环遍历表数据并将其发送到服务器
- email - 添加转发过滤器时未验证电子邮件地址 (AWS SES)
- php - 如何在 Laravel 中编辑和更新复选框值?
- javascript - 如何在卡片中模拟 Airbnb 风格的滑块?
- spring - Spring Junit 测试中的模拟类变量显示 Null
- windows - 在 Word 女士中导出 pdf 后的空白页
- c++ - 如何在使用区域时创建选项?
- python - 使用 Selenium 访问输入元素的日期文本
- c - 你能把特殊字符放在表格里吗?
- javascript - JavaScript 对数字数组的特定部分进行加减运算