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]
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab