如何让Elixir Websockex订阅Websocket? [英] How do I get Elixir Websockex to subscribe to a websocket?

查看:62
本文介绍了如何让Elixir Websockex订阅Websocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Elixir/Erlang的新手.举例来说,我正在尝试学习如何订阅Websocket提要.

I'm a newbie to Elixir/Erlang. By way of example, I'm trying to learn how to subscribe to a websocket feed.

我已经复制了Websockex基本示例:

I've copied the Websockex basic example:

defmodule WebSocketExample do
  use WebSockex

  def start_link(url, state) do
    WebSockex.start_link(url, __MODULE__, state)
  end

  def handle_frame({type, msg}, state) do
    IO.puts "Received Message - Type: #{inspect type} -- Message: #{inspect msg}"
    {:ok, state}
  end

  def handle_cast({:send, {type, msg} = frame}, state) do
    IO.puts "Sending #{type} frame with payload: #{msg}"
    {:reply, frame, state}
  end
end

并尝试使用以下方法在iex中实例化它:

and am trying to instantiate it in iex with:

WebSocketExample.start_link "wss://www.bitmex.com/realtime?subscribe=instrument,quote:XBTUSD", state

(CompileError) iex:3: undefined function state/0

但是我收到状态未定义的错误.

however I get the error that state is undefined.

我不确定应该是什么状态(肯定是空的并且在循环中传递?).任何帮助我理解的技巧将不胜感激!

I'm not sure what state should be (surely that's empty and gets passed around a loop?). Any tips that help me understand would be much appreciated!

推荐答案

state 此处可以是任何值.您可以使用它来存储有关套接字实例的信息,以后可以在句柄函数中对其进行访问.例如,您可以将用户ID传递给 start_link ,并从 handle_cast handle_info 访问该ID.如果您不想保留任何状态,只需传递任何值即可,例如:ok :

state here can be any value. You can use it to store information about the socket instance which can later be accessed in the handle functions. For example, you can pass a user id to start_link and access that from handle_cast and handle_info. If you don't want to keep any state, just pass any value, e.g. :ok:

WebSocketExample.start_link "wss://...", :ok

这篇关于如何让Elixir Websockex订阅Websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆