我想将捕获的图像从树莓派客户端(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套接字通信过程错误,或者是否还有其他问题,请告诉我。
最佳答案
代码存在多个问题。在客户端:
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 = '';
关于javascript - 如何使用tcp套接字将图像从[python客户端]发送到[node.js服务器]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58036874/