亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在同一結構中使用多個通道

如何在同一結構中使用多個通道

Go
阿晨1998 2023-01-03 14:08:02
在我的代碼中,我想執行以下操作:從輸入接收數據event和message根據接收到的數據格式化event我想使用與 OOP 中的方法接近的東西,但看起來我搞砸了。我寫的是:// Define the structs that contains the channelstype sseData struct {    event, message string}type DataPasser struct {    data       chan sseData    logs       chan string    connection chan struct{} // To control maximum allowed clients connections}// DEfine the struct's reciever that do the formating based on the input datefunc (p *DataPasser) Format() {    data := <-p.data    switch {    case len(data.event) > 0:        p.logs <- fmt.Sprintf("event: %v\ndata: %v\n\n", data.event, data.message)    case len(data.event) == 0:        p.logs <- fmt.Sprintf("data: %v\n\n", data.message)    }}然后我有以下內容:func (p *DataPasser) HandleSignal(w http.ResponseWriter, r *http.Request) {    w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")    w.Header().Set("Cache-Control", "no-cache")    w.Header().Set("Connection", "keep-alive")    setupCORS(&w, r)    fmt.Println("Client connected from IP:", r.RemoteAddr)    p.connection <- struct{}{}    flusher, ok := w.(http.Flusher)    if !ok {        http.Error(w, "Internal error", 500)        return    }    fmt.Fprint(w, "event: notification\ndata: Connection to WhatsApp server ...\n\n")    flusher.Flush()    // Connect to the WhatsApp client    go Connect()    // Prepare dataParser `p` to recieve data through its sseData channel    go p.Format()    for {        select {        case c := <-p.logs:            fmt.Fprint(w, c)            flusher.Flush()        case <-r.Context().Done():            <-p.connection            fmt.Println("Connection closed")            return        }    }}
查看完整描述

2 回答

?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

當您passer.datago connect()例程向其發送數據時,例程go p.Format()不在監聽。因為您使用的是無緩沖通道parser.data但沒有接收器正在監聽,所以您的代碼被卡住了。要么使用緩沖通道,parser.data要么確保您的例程監聽來自數據通道的傳入消息已啟動,并在實際將數據發送到通道之前進行監聽。在你的情況下,我想在Format例程之前開始例程Connect就足夠了。



查看完整回答
反對 回復 2023-01-03
?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

我通過寫解決了它:


    // Connect to the WhatsApp client

    go Connect()


    for {

        select {

        case data := <-p.data:

            fmt.Println("recieved")


            switch {

            case len(data.event) > 0:

                fmt.Fprintf(w, "event: %v\ndata: %v\n\n", data.event, data.message)

            case len(data.event) == 0:

                fmt.Fprintf(w, "data: %v\n\n", data.message)

            }

            flusher.Flush()

        case <-r.Context().Done():

            <-p.connection

            fmt.Println("Connection closed")

            return

        }

    }

但我仍然對拆分操作和使用接收器感興趣,我不能接受這個作為答案,因為它是問題的解決方案,但不是問題的答案。任何想法?


查看完整回答
反對 回復 2023-01-03
  • 2 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號