gpt4 book ai didi

go - 为什么 io.Copy 会引发 NetworkIdleTimeout 错误?

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:07 27 4
gpt4 key购买 nike

请考虑下面的可运行示例。

package main

import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"io"
"log"
"math/big"
"time"

quic "github.com/lucas-clemente/quic-go"
)

// var qc = &quic.Config{Versions: []quic.VersionNumber{101}}
var qc *quic.Config

// GenerateTLSConfig creates bare-bones TLS config for the server
func GenerateTLSConfig() *tls.Config {
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
panic(err)
}

// generate a random serial number (a real cert authority would have some logic behind this)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
panic("failed to generate serial number: " + err.Error())
}

template := x509.Certificate{
SerialNumber: serialNumber,
// DNSNames: []string{"localhost"}, // keep mint happy
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 87600), // in 10 years
BasicConstraintsValid: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
panic(err)
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})

tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
panic(err)
}
return &tls.Config{
Certificates: []tls.Certificate{tlsCert},
InsecureSkipVerify: true,
}
}

func server() (quic.Listener, error) {
return quic.ListenAddr("localhost:9001", GenerateTLSConfig(), qc)
}

func accept(l quic.Listener) (quic.Session, error) {
return l.Accept()
}

func acceptStream(sess quic.Session) (quic.Stream, error) {
return sess.AcceptStream()
}

func client() (quic.Session, error) {
return quic.DialAddr("localhost:9001", GenerateTLSConfig(), qc)
}

func openStream(sess quic.Session) (quic.Stream, error) {
return sess.OpenStreamSync()
}

func main() {
ch := make(chan struct{})

go func() {
l, err := server()
if err != nil {
log.Fatal("failed to listen:", err)
}

sess, err := accept(l)
if err != nil {
log.Fatal("failed to accept session:", err)
}

s, err := acceptStream(sess)
if err != nil {
log.Fatal("failed to accept stream:", err)
}

log.Println("stream accepted")

// b := make([]byte, len("hello, world"))
// if _, err = s.Read(b); err != nil {
// log.Fatal("failed to read from stream:", err)
// }
// log.Println(string(b))

buf := bytes.NewBuffer(make([]byte, len("hello, world")))
if _, err = io.Copy(buf, s); err != nil {
log.Fatal("failed to read from stream:", err)
}
log.Println(buf.String())

close(ch)
}()

sess, err := client()
if err != nil {
log.Fatal("failed to dial:", err)
}

s, err := openStream(sess)
if err != nil {
log.Fatal("failed to open stream:", err)
}

log.Print("writing")
if _, err = io.Copy(s, bytes.NewBuffer([]byte("hello, world"))); err != nil {
log.Fatal("failed to write:", err)
}
log.Print("wrote")

<-ch
}

运行此示例将产生以下输出:

$ go run cmd/scratch/main.go                                                                                                    (656ms)
2018/05/19 13:09:17 writing
2018/05/19 13:09:17 wrote
2018/05/19 13:09:17 stream accepted
2018/05/19 13:09:47 failed to read from stream:NetworkIdleTimeout: No recent network activity.
exit status 1

改变

buf := bytes.NewBuffer(make([]byte, len("hello, world")))
if _, err = io.Copy(buf, s); err != nil {
log.Fatal("failed to read from stream:", err)
}
log.Println(buf.String())

b := make([]byte, len("hello, world"))
if _, err = s.Read(b); err != nil {
log.Fatal("failed to read from stream:", err)
}
log.Println(string(b))

似乎解决了这个问题。

问题:

为什么在这种情况下不能将 io.Copybytes.Buffer 一起使用?

最佳答案

这与您对 bytes.Buffer 的使用无关。相反,io.Copy 等待 EOF。 Read 只是读取当前存在的内容。如果您的流从未关闭,io.Copy 将永远不会完成。

这意味着,在所有其他条件相同的情况下,无论您使用 io.Copy 还是 Read 都会发生超时 - 您在使用时可能不会注意到它Read,因为Read是立即返回的,30秒后才会超时。

关于go - 为什么 io.Copy 会引发 NetworkIdleTimeout 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50425180/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com