首页 > 解决方案 > 如何使用 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通信过程有误,或者还有其他问题,请告诉我。

标签: javascriptpythonnode.jssocketstcp

解决方案


代码存在多个问题。在客户端:

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 = '';

推荐阅读