为了账号安全,请及时绑定邮箱和手机立即绑定

我们可以向客户端发送请求表单服务器并通过 quic/http3 获得响应吗?

我们可以向客户端发送请求表单服务器并通过 quic/http3 获得响应吗?

Go
万千封印 2022-12-19 10:56:24
我正在quic-go用来实现我的想法,我需要服务器转发请求给客户端以获得响应,就像我们通常客户端向Web服务器发送请求一样。但是quic-go,在建立连接后,服务器可以初始化流以向客户端发送请求并获得响应吗?我做了一个尝试,但没有成功。下面的代码来自echo.go示例目录,注释行之间的两部分是我添加的。package mainimport (    "context"    "crypto/rand"    "crypto/rsa"    "crypto/tls"    "crypto/x509"    "encoding/pem"    "fmt"    "io"    "log"    "math/big"    "github.com/lucas-clemente/quic-go")cost addr = "localhost:4242"const message = "foobar"// We start a server echoing data on the first stream the client opens,// then connect with a client, send the message, and wait for its receipt.func main() {    go func() { log.Fatal(echoServer()) }()    err := clientMain()    if err != nil {        panic(err)    }}// Start a server that echos all data on the first stream opened by the clientfunc echoServer() error {    listener, err := quic.ListenAddr(addr, generateTLSConfig(), nil)    if err != nil {        return err    }    conn, err := listener.Accept(context.Background())    if err != nil {        return err    }    stream, err := conn.AcceptStream(context.Background())    if err != nil {        panic(err)    }    // Echo through the loggingWriter    _, err = io.Copy(loggingWriter{stream}, stream)    if err != nil {        panic(err)    }    //------------------------------    stream1, err := conn.OpenStream()    if err != nil {        panic(err)    }    message := "aaaaa"    fmt.Printf("2-Server: Sending '%s'\n", message)    _, err = stream1.Write([]byte(message))    //------------------------------    return err}func clientMain() error {    tlsConf := &tls.Config{        InsecureSkipVerify: true,        NextProtos:         []string{"quic-echo-example"},    }    conn, err := quic.DialAddr(addr, tlsConf, nil)    if err != nil {        return err    }    stream, err := conn.OpenStreamSync(context.Background())    if err != nil {        return err    }       
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

你很接近。


log.Fatal请注意服务器如何写入,然后返回,它在客户端有机会读取和处理数据之前伸出手。


注意message变量,一个是 6 长,另一个只有 5 长。


正确关闭你的流,服务器没有结束它在移交之前就结束了;


package main


import (

    "context"

    "crypto/rand"

    "crypto/rsa"

    "crypto/tls"

    "crypto/x509"

    "encoding/pem"

    "fmt"

    "io"

    "log"

    "math/big"


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

)


const addr = "localhost:4242"


const message = "foobar"


// We start a server echoing data on the first stream the client opens,

// then connect with a client, send the message, and wait for its receipt.

func main() {

    go func() {

        err := echoServer()

        if err != nil {

            log.Println(err)

        }

    }()


    err := clientMain()

    if err != nil {

        panic(err)

    }

}


// Start a server that echos all data on the first stream opened by the client

func echoServer() error {

    listener, err := quic.ListenAddr(addr, generateTLSConfig(), nil)

    if err != nil {

        return err

    }

    conn, err := listener.Accept(context.Background())

    if err != nil {

        return err

    }

    stream, err := conn.AcceptStream(context.Background())

    if err != nil {

        panic(err)

    }

    // Echo through the loggingWriter

    _, err = io.Copy(loggingWriter{stream}, stream)

    if err != nil {

        log.Println(err)

        return err

    }


    //------------------------------

    fmt.Printf("Server: open stream\n")

    stream1, err := conn.OpenStream()

    if err != nil {

        return err

    }


    fmt.Printf("2-Server: Sending '%s'\n", message)


    var n int

    n, err = stream1.Write([]byte(message))

    fmt.Printf("Server: write %v %v\n", n, err)

    stream1.Close()

    //------------------------------

    return err

}


func clientMain() error {

    tlsConf := &tls.Config{

        InsecureSkipVerify: true,

        NextProtos:         []string{"quic-echo-example"},

    }

    conn, err := quic.DialAddr(addr, tlsConf, nil)

    if err != nil {

        return err

    }


    stream, err := conn.OpenStreamSync(context.Background())

    if err != nil {

        return err

    }


    fmt.Printf("Client: Sending '%s'\n", message)

    _, err = stream.Write([]byte(message))

    if err != nil {

        return err

    }


    buf := make([]byte, len(message))

    _, err = io.ReadFull(stream, buf)

    if err != nil {

        return err

    }

    fmt.Printf("Client: Got '%s'\n", buf)

    err = stream.Close()

    if err != nil {

        return err

    }


    //-------------------------------

    for {

        fmt.Printf("Client: accept stream\n")

        stream1, err := conn.AcceptStream(context.Background())

        if err != nil {

            return err

        }


        fmt.Printf("Client: got stream %v\n", err)

        buf1 := make([]byte, len(message))

        _, err = io.ReadFull(stream1, buf1)

        if err != nil {

            return err

        }

        fmt.Printf("2-Client: Got '%s'\n", buf1)


        err = stream1.Close()

        if err != nil {

            return err

        }

        break

    }

    //-------------------------------


    return nil

}


// A wrapper for io.Writer that also logs the message.

type loggingWriter struct{ io.Writer }


func (w loggingWriter) Write(b []byte) (int, error) {

    fmt.Printf("Server: Got '%s'\n", string(b))

    return w.Writer.Write(b)

}


// Setup a bare-bones TLS config for the server

func generateTLSConfig() *tls.Config {

    key, err := rsa.GenerateKey(rand.Reader, 1024)

    if err != nil {

        panic(err)

    }

    template := x509.Certificate{SerialNumber: big.NewInt(1)}

    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},

        NextProtos:   []string{"quic-echo-example"},

    }

}



查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信