从 WebSocket 客户端获取通道值

huangapple go评论93阅读模式
英文:

getting channel value from a webscoket client

问题

你的问题是在将响应从客户端传递到主文件中的通道时遇到了问题。目前,该通道只返回一个空值,然后不再返回任何内容。在将值传递给通道时似乎存在问题。你想知道如何解决这个问题。

根据你提供的代码,问题可能出在以下几个地方:

  1. PubListen函数中,你将res的值发送到通道ch之后立即打印resch的值。这可能导致打印出空值,因为在发送到通道之前,res可能还没有被赋值。你可以尝试在发送到通道之前打印res的值,看看是否有值。

  2. 你在main函数中创建了一个goroutine来接收通道ch的值并打印它们。但是,你没有等待该goroutine完成,就立即调用了cancel()函数和wg.Wait()函数。这可能导致在goroutine还没有完成时就关闭了通道,从而导致无法接收到所有的值。你可以尝试在调用cancel()wg.Wait()之前等待该goroutine完成。

请尝试根据上述建议进行修改,并检查是否解决了问题。如果问题仍然存在,请提供更多的信息和错误消息,以便我可以更好地帮助你。

英文:

I'm running a websocket client and want to pass the response(s) from the client to a channel that i can work with in my main file. Currently, the channel just returns a nil value once and then nothing else. I seem to have an issue when passing a value to the channel. Any help? Here is what I've done so far

package main

import (
	"context"
	"fmt"
	"kraken_client/stored_data"
	"kraken_client/ws_client"
	"os"
	"os/signal"
	"strings"
	"sync"
	"syscall"
)

func main() {
	// check if in production or testing mode & find base curency
	var testing bool = true
	args := os.Args
	isTesting(args, &testing, &stored_data.Base_currency)

	// go routine handler
	comms := make(chan os.Signal, 1)
	signal.Notify(comms, os.Interrupt, syscall.SIGTERM)
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	var wg sync.WaitGroup

	// set ohlc interval and pairs
	OHLCinterval := 5
	pairs := []string{"BTC/" + stored_data.Base_currency, "EOS/" + stored_data.Base_currency}

	// create ws connections
	pubSocket, err := ws_client.ConnectToServer("public", testing)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// listen to websocket connections
	ch := make(chan interface{})
	wg.Add(1)
	go pubSocket.PubListen(ctx, &wg, ch, testing)

	// subscribe to a stream
	pubSocket.SubscribeToOHLC(pairs, OHLCinterval)

	go func() {
		for c := range ch {
			fmt.Println(c)
		}
	}()

	<-comms
	cancel()
	wg.Wait()
	defer close(ch)
}

Here is how the PubListen function works

func (socket *Socket) PubListen(ctx context.Context, wg *sync.WaitGroup, ch chan interface{}, testing bool) {
	defer wg.Done()
	defer socket.Close()

	var res interface{}

	socket.OnTextMessage = func(message string, socket Socket) {
		//log.Println(message)
		res = pubJsonDecoder(message, testing) // this function decodes the message and returns an interface
		log.Println(res) // this is printing the correctly decoded value.

	}

	ch <- res
	log.Println(res) // does not print a value
	log.Println(ch) // does not print a value

	<-ctx.Done()
	log.Println("closing public socket")
	return
}

What am I doing wrong?

答案1

得分: 1

问题中的代码在PubListen函数中执行了一次ch <- res语句,而在resOnTextMessage函数设置之前。

要在每个消息中向ch发送一个值,将ch <- res这一行移到OnTextMessage函数中。该函数会为每个消息调用一次。

func (socket *Socket) PubListen(ctx context.Context, wg *sync.WaitGroup, ch chan interface{}, testing bool) {
    defer wg.Done()
    defer socket.Close()
    socket.OnTextMessage = func(message string, socket Socket) {
        res := pubJsonDecoder(message, testing)
        ch <- res
        log.Println(res)
    }
    <-ctx.Done()
    log.Println("closing public socket")
    return
}
英文:

The code in the question executes the statement ch &lt;- res once from PubListen before the res is set by the OnTextMessage function.

To send a value to ch on each message, move the line ch &lt;- res to the OnTextMessage function. That function is called once for each message.

func (socket *Socket) PubListen(ctx context.Context, wg *sync.WaitGroup, ch chan interface{}, testing bool) {
    defer wg.Done()
    defer socket.Close()
    socket.OnTextMessage = func(message string, socket Socket) {
        res := pubJsonDecoder(message, testing)
        ch &lt;- res
        log.Println(res)
    }
    &lt;-ctx.Done()
    log.Println(&quot;closing public socket&quot;)
    return
}

huangapple
  • 本文由 发表于 2022年6月2日 12:53:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/72470827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定