How to connect two Elixir nodes via local network?

前端 未结 2 1953
失恋的感觉
失恋的感觉 2020-12-23 19:16

How can I connect two Erlang/Elixir-nodes of two different machines via network connection?

相关标签:
2条回答
  • 2020-12-23 19:56

    If you are trying to connect Nodes via code: You need to turn your running code into a distributed node. To do this run Node.start(:fullNameOfServer).

    Eg: if your IP is 192.168.0.1, you can have a full Node name like :"foo@192.168.0.1"

    Once you turn your node into a distributed node, you set the cookie: Node.set_cookie :cookie_name

    Finally, you need to establish a connection with the remote Node. (You also need to Node.start and Node.set_cookie on the remote node) To do this, you need the remote node's name. Let us assume the remote node's name is bar@192.168.0.2 (assuming this Node is another computer on the same local network). The code to do this, looks like Node.connect :"bar@192.168.0.2"

    You can now run Node.list to see the bar@192.168.0.2 available on foo@192.168.0.1 and vice versa.

    Summarising the above points, your code should look something like

    On the Foo machine

    Node.start :"foo@192.168.0.1" #this is the IP of the machine on which you run the code
    Node.set_cookie :cookie_name
    Node.connect "bar@192.168.0.2"
    

    On the Bar machine

    Node.start :"bar@192.168.0.2" 
    Node.set_cookie :cookie_name
    
    0 讨论(0)
  • 2020-12-23 19:59

    You have to name your nodes and use the same cookie on both nodes.

    In machine 1:

    iex --name node1@machine1.com --cookie a_cookie_string
    

    In machine 2:

    iex --name node2@machine2.com --cookie a_cookie_string
    

    Now the two machines can communicate. To test it, you can do something like this, on machine1:

    iex(node1@machine1.com)1> Node.connect :"node2@machine2.com"
    true
    
    iex(node1@machine1.com)2> print_node_name = fn -> IO.puts Node.self end
    #Function<erl_eval.20.80484245>
    
    iex(node1@machine1.com)3> Node.spawn(:"node2@machine2.com", print_node_name)
    node2@machine2.com
    #PID<7789.49.0> 
    

    Domain names machine1.com and machine2.com can be changed with the ip addresses of the machines as well.

    0 讨论(0)
提交回复
热议问题