douxingti9307 2013-11-24 16:17
浏览 24
已采纳

从stdin接收二进制数据,然后发送到Go中的通道

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条回答 默认 最新

  • dopzc64662 2013-11-24 18:39
    关注

    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...):

    func input(dc chan []byte) {
        defer close(dc)
        for {
            data := make([]byte, 2)
            n, err := os.Stdin.Read(data)
            if n > 0 {
                dc <- data[0:n]
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊