简体   繁体   English

将图像缓冲区发送到node.js TCP服务器

[英]Sending image buffer to node.js tcp server

I am trying to send image data from my TCP client to my TCP server both written in node.js 我试图将图像数据从我的TCP客户端发送到我的TCP服务器,两者均以node.js编写

I have already tried doing it this way 我已经尝试过这样做

client: 客户:

function onData(socket, data) {
  var data = Buffer.from(data).toString()
  var arg = data.split(',')
  var event = arg[0]
  console.log(event)

  if (event == 'screenshot') {
    console.log(hostname)
    console.log('control client uid ' + arg[1] + 'then we screenshot')
    screenshot()
      .then(img => {
        console.log(img)
        socket.write('screenshotData,' + ',' + hostname + ',' + img)
        socket.write('stdout,' + arg[2] + ',Screenshot')
      })
      .catch(err => {
        console.log(err)
        socket.write('error', err)
      })
  }
}

server: 服务器:

sock.on('data', function(data) {
  //right here i need to parse the first 'EVENT' part of the text so i can get cusotom tcp events and
  var data = Buffer.from(data).toString()
  var arg = data.split(',')
  var event = arg[0]

  if (event == 'screenshotData') {
    agentName = arg[1]
    img = arg[2]
    console.log('agent-name ' + agentName)
    console.log('screnshotdata' + img)

    var dt = dateTime.create()
    var formattedTime = dt.format('Y-m-d-H-M-S')
    var folder = 'adminPanel/screenshots/'
    var filename = formattedTime + '-' + agentName + '.png'
    console.log(filename)
    fs.writeFile(folder + filename, img, function(err) {
      console.log(err)
    })
  }
})

I had to build some rudimentary event system in TCP. 我必须在TCP中构建一些基本的事件系统。 If you know a better way then let me know. 如果您知道更好的方法,请告诉我。 Anyways, the client takes a screenshot and then it does socket.write('screenshotData', + ',' + hostname + ',' img) . 无论如何,客户端都会截取屏幕截图,然后执行socket.write('screenshotData', + ',' + hostname + ',' img)

But it sends the data in multiple chunks as my console is showing random gibberish as a new event many times so I don't even know how I would do this. 但是它以多个块的形式发送数据,因为我的控制台多次将随机垃圾显示为新事件,所以我什至不知道该怎么做。 Any help would be great. 任何帮助都会很棒。

You are treating your TCP stream as a message-oriented protocol, in addition to mixing encodings (your image Buffer is simply concatenated into the string). 除了混合编码之外,您还将TCP流视为面向消息的协议(您的图像Buffer只是连接到字符串中)。

I suggest you switch TCP streams with websockets . 我建议您使用websockets切换TCP流。 The interface remains largely the same ( read replaced with message events, stuff like that) but it actually behaves like you are expecting. 该界面基本上保持不变(用message事件代替read ,诸如此类),但实际上它的行为符合您的期望。

Working server : 工作服务器

const WebSocket = require('ws');
const fs = require('fs');

const PORT = 3000;

const handleMessage = (data) => {
    const [action, payload] = data.split(',');
    const imageData = Buffer.from(payload, 'base64');

    const imageHandle = fs.createWriteStream('screenshot.jpg');
    imageHandle.write(imageData);
    imageHandle.end();

    console.log(`Saved screenshot (${imageData.length} bytes)`);
};

const wss = new WebSocket.Server({port: PORT});
wss.on('connection', (ws) => {
    console.log('Opened client');
    ws.on('message', (data)=>handleMessage(data));
});
console.log('Server started');

client : 客户

const WebSocket = require('ws');
const screenshot = require('screenshot-desktop');

const PORT = 3000;

const sendImage = ( client, image ) => {
    const payload = image.toString('base64');
    const message = ["screenshot", payload].join(',');
    console.log(`Sending ${image.length} bytes in message ${message.length} bytes`);
    client.send(
        message, 
        () => {
            console.log('Done');
            process.exit(0);
        }
    );
};

const client = new WebSocket('ws://localhost:'+PORT+'/');
client.on('open', () => {
    console.log('Connected');
    screenshot().then( image => sendImage(client, image) );
});

if you specifically want to transfer an image type file, then the best-suggested way is to deal with b64 data. 如果您特别想传输图像类型文件,则建议的最佳方法是处理b64数据。 ie convert your image to a b64 and send the data over a channel, and after receiving it in the server, you can convert it into a .jpg/.png again. 将图像转换为b64并通过通道发送数据,然后在服务器中将其接收后,可以再次将其转换为.jpg / .png。

For reference https://www.npmjs.com/package/image-to-base64 供参考https://www.npmjs.com/package/image-to-base64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM