在两个节点 erlang 之间传递数据

问题描述 投票:0回答:1

我最近开始学习Erlang,我正在尝试实现一个服务器-客户端示例程序。我已经创建了一个注册进程,我想从另一个进程向它发送数据。代码如下

-module(mine).
-export([alice/0, bob/2, startAlice/0, startBob/1]).

alice() ->
    receive
        {message, BobNode} ->
            io:fwrite("Alice got a message \n"),
            BobNode ! message,
            alice()
        finished -> io:fwrite("Alice is finished\n")
    end.

bob(0, AliceNode) ->
    {alice, AliceNode} ! finished,
    io:fwrite("Bob is finished\n");

bob(N, AliceNode) ->
    {alice, AliceNode} ! {message, self()},
    receive
        message -> io:fwrite("Bob got a message ~w \n",[N])
    end,
    bob(N-1, AliceNode).

startAlice() ->
    register(alice, spawn(mine, alice, [])).

startBob(AliceNode) ->
    spawn(mine, bob, [30000, AliceNode]).

在这里,我想从 bob 向 alice 发送一些值,比如 N。我尝试将数据发送为

{alice, AliceNode, Nvalue} ! {message, self(), N}
bob(N, AliceNode)
函数中,但得到错误变量 'Nvalue' is unbound erl。我确定我在这里遗漏了一些微不足道的东西。任何帮助,将不胜感激。提前致谢。

process erlang message-passing
1个回答
0
投票

查看更改后的代码:

-module(mine).
-export([alice/0, bob/2, startAlice/0, startBob/1]).

alice() ->
    receive
        {X, BobNode} ->
            io:fwrite("Alice got a message ~w \n",[X]),
            BobNode ! message,
            alice();
        finished -> io:fwrite("Alice is finished\n")
    end.

bob(0, AliceNode) ->
    {alice, AliceNode} ! finished,
    io:fwrite("Bob is finished\n");

bob(N, AliceNode) ->
    {alice, AliceNode} ! {N, self()},
    receive
        message -> io:fwrite("Bob got a message ~w \n",[N])
    end,
    bob(N-1, AliceNode).

startAlice() ->
    register(alice, spawn(mine, alice, [])).

startBob(AliceNode) ->
    spawn(mine, bob, [10, AliceNode]).

我用过erlang: Erlang/OTP 23 [erts-11.1.8] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]

12> c(mine).            
    {ok,mine}
13> mine:startAlice().    
    true
14> mine:startBob(node()).
爱丽丝收到消息 10
<0.93.0>
鲍勃收到消息 10
爱丽丝收到消息 9
鲍勃收到消息 9
爱丽丝收到消息 8
鲍勃收到消息 8
爱丽丝收到消息 7
鲍勃收到消息 7
爱丽丝收到消息 6
鲍勃收到消息 6
爱丽丝收到消息 5
鲍勃收到消息 5
爱丽丝收到消息 4
鲍勃收到消息 4
爱丽丝收到消息 3
鲍勃收到消息 3
爱丽丝收到消息 2
鲍勃收到消息 2
爱丽丝收到消息 1
鲍勃收到消息 1
鲍勃完成了
爱丽丝完了

我认为发送和接收部分应该是同步的。

{alice, AliceNode, Nvalue} ! {message, self(), N}

需求:

alice() ->
    receive
        {message, BobNode, X} ->
            io:fwrite("Alice got a message ~w \n",[X]),
            BobNode ! message,
            alice();
        finished -> io:fwrite("Alice is finished\n")
    end.
© www.soinside.com 2019 - 2024. All rights reserved.