javascript - 如何使用 tcp 套接字将图像从 [python 客户端] 发送到 [node.js 服务器]?
问题描述
我想将捕获的图像从树莓派客户端(python)发送到服务器(node.js)。我们将图像编码为 base64 并使用将 base64 解码为图像将其发送回服务器,但由于文件格式不同,图像被破坏了。
这是我的代码:
客户端.py
import base64
from PIL import Image
import os, sys
ip = ''
port = 3008
s = socket.socket()
s.connect((ip, port))
image_path = '/home/pi/TCPproject/test.jpg'
if image_path != '':
with open(image_path, "rb") as imageFile:
image_data = base64.b64encode(imageFile.read())
else:
image_data = 'cusdom_image'
s.send(image_data)
s.close()
服务器.js
var fs = require('fs');
var base64ToImage = require('base64-to-image');
var sockets = [];
var server = net_server.createServer(function(client) {
console.log('Client connection: ');
console.log('local = %s:%s', client.localAddress, client.localPort);
console.log('remote = %s:%s', client.remoteAddress, client.remotePort);
client.setTimeout(500);
client.setEncoding('utf8');
sockets.push(client);
var imageData;
client.on('data', function(data) {
imageData+= data;
});
client.on('end', function() {
console.log('end!')
var decoded = Buffer.from(imageData, 'base64');
fs.writeFile("test.jpg", decoded, function (err) {
if (err) throw err;
else console.log('Saved!');
});
});
client.on('error', function(err) {
console.log('Socket Error: ', JSON.stringify(err));
});
client.on('timeout', function() {
console.log('Socket Timed out');
});
});
server.listen(3008, function() {
console.log('Server listening: ' + JSON.stringify(server.address()));
server.on('close', function(){
console.log('Server Terminated');
});
server.on('error', function(err){
console.log('Server Error: ', JSON.stringify(err));
});
});
function writeData(socket, data){
var success = socket.write(data);
if (!success){
console.log("Client Send Fail");
}
}
如果编码、解码有误,或者TCP socket通信过程有误,或者还有其他问题,请告诉我。
解决方案
代码存在多个问题。在客户端:
s.send(image_data)
这可能会发送image_data
,但它可能只发送一部分,image_data
因为send
不能保证发送所有内容。用于sendall
发送所有内容或检查返回值send
并确保稍后发送其余内容,如果不是一次发送所有内容。
在服务器端:
var imageData;
client.on('data', function(data) {
imageData+= data;
});
client.on('end', function() {
console.log('end!')
var decoded = Buffer.from(imageData, 'base64');
如果您imageData
在解码之前查看一下,您会看到它以字符串开头,undefined
然后才是 base64 数据。但所有这些都被视为 base64 解码器的输入,导致数据损坏。要修复此初始化imageData
:
var imageData = '';
推荐阅读
- android - 图片方向不对。如何修复它
- binding - 使用联合的 jaxb 绑定 simpleType 不会创建枚举
- laravel - 通过 API 将帖子从 facebook 分享到 instagram
- c++ - C++ 编译器选项允许在相互利用的类中使用不完整类型?
- javascript - 渲染元素 onClick 事件,React JS
- android - tts 文件未从 Android 上的 api 29 或更高版本保存
- git - Bitbucket 服务器 API:查找分支的合并库
- typescript - 在 Serenity 平台中保存之前自动填充客户 ID 字段
- apache-spark - 如何在带有delemter |@|的spark sql中使用Split函数?
- arrays - 如何提取数组中的数字