Receiving binary data from stdin, sending to channel in Go

◇◆丶佛笑我妖孽 提交于 2019-12-25 02:39:04

问题


so I have the following test Go code which is designed to read from a binary file through stdin, and send the data read to a channel, (where it would then be processed further). In the version I've given here, it only reads the first two values from stdin, although that's fine as far as showing the problem is concerned.

package main

import (
    "fmt"
    "io"
    "os"
)

func input(dc chan []byte) {
    data := make([]byte, 2)
    var err error
    var n int
    for err != io.EOF {
        n, err = os.Stdin.Read(data)
        if n > 0 {
            dc <- data[0:n]
        }
    }
}

func main() {
    dc := make(chan []byte, 1)
    go input(dc)
    fmt.Println(<-dc)
}

To test it, I first build it using go build, and then send data to it using the command-

./inputtest < data.bin

The data I am using currently to test is just random binary data created using the openssl command.

The problem I am having is that it misses the first values from Stdin, and only gives the second and greater values. I think this is to do with the channel, as the same script with the channel removed produces the correct data. Has anyone come across this before? For example, I get the following output when running this command-

./inputtest < data.bin
[36 181]

Whereas I should be getting-

./inputtest < data.bin
[72 218]

(The binary data is the same in both instances.)


回答1:


You're overwriting your buffer on every read and you've got a channel buffer, so you'll lose data every time there's space in the channel.

Try something like this (not tested, written on tablet, etc...):

import "os"

func input(dc chan []byte) error {
    defer close(dc)
    for {
        data := make([]byte, 2)
        n, err := os.Stdin.Read(data)
        if n > 0 {
            dc <- data[0:n]
        }
        if err != nil {
            return err
        }
    }
    return nil
}


来源:https://stackoverflow.com/questions/20176796/receiving-binary-data-from-stdin-sending-to-channel-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!