数据无法通过FIFO正确传输

时间:2017-06-03 01:54:05

标签: c node.js pipe buffer fifo

我正在尝试使用FIFO将MP3缓冲区从C程序传输到node.js程序。我这样做是通过在动态内存中缓冲MP3段然后在准备就绪时将其发送到node.js。

我的C代码

void send_buffer(buffer* buff)
{
    // if the buffer was not filled
    if(buff == NULL)
    {
        return;
    }
//signal(SIGPIPE,SIG_IGN);
// Attempts to open connection and returns INVALID on failure
int port = open("/tmp/radio", O_WRONLY | O_NONBLOCK);
if(port != -1)
{   
    // Allocates enough memory for the header that will be sent to 
    char* segment = toBYTES(buff);

    // checks if memory allocation failed   
    if(segment == NULL)
    {
        return;
    }

    // saving it to a file to make sure the data in the buffer is correct
    FILE* file = fopen("temp.mp3", "a");
    if(file != NULL)
    {
        fwrite(segment, buff->size, 1, file);
        fclose(file);
    }

    // writes to the node
    char* orig_segment = segment; // will point to the first element of the original buffer
    // writes to the node
    int n_bytes = 0;
    while ((n_bytes = write(port, segment, buff->size)) != buff->size)
    {
        segment += n_bytes;
    }   
    close(port);        
    free(orig_segment);
}

我很确定动态内存中的缓冲区数据是正确的,因为我尝试按代码所示编写它,文件正确地在媒体播放器中播放。

另一方面,我的节点js

var strict = require('use-strict');
var FIFO = require('fifo-js');
// establishing connection through the FIFO
var fifo = new FIFO("/tmp/radio");
// reading data from the fifo
fifo.setReader(function(data){
var fs = require('fs');
if(data.length != 0)
    fs.appendFile('temp.mp3', data);
});

我也尝试写出通过FIFO接收的数据;然而,与c程序不同,媒体播放器表示该文件已损坏且无法播放。我甚至检查了传递给Node.js的字符串的长度,它通常是一个长度为零的字符串。我在这里错过了什么?有没有更好的方法将相对较大的数据从一个程序传输到另一个程序?

0 个答案:

没有答案