将Erlang-C端口示例转换为Erlang-Golang

将Erlang-C端口示例转换为Erlang-Golang,第1张

将Erlang-C端口示例转换为Erlang-Golang

根据@Justin发布此答案,该问题包含略有不同但有效的答案。

echo.go

package mainimport (    "bufio"    "os")func main() {    for{        reader := bufio.NewReader(os.Stdin)        bytes, _ := reader.ReadBytes('n')        os.Stdout.Write(bytes)    }}

complex1.erl

-module(complex1).-export([start/1, stop/0, init/1]).-export([send/1]).start(ExtPrg) ->    spawn_link(?MODULE, init, [ExtPrg]).stop() ->    complex ! stop.send(Y) -> call_port({msg, Y}).call_port({msg, Msg}) ->    complex ! {call, self(), Msg},    receive    {complex, Result} ->        Result    end.init(ExtPrg) ->    register(complex, self()),    process_flag(trap_exit, true),    Port = open_port({spawn, ExtPrg}, []),    loop(Port).loop(Port) ->    receive    {call, Caller, Msg} ->        Port ! {self(), {command, Msg++[10]}},        Data = receive_all(Port, 100),        Caller ! {complex, Data},        loop(Port);    stop ->        Port ! {self(), close},        receive {Port, closed} -> exit(normal)        end;    {'EXIT', Port, Reason} ->        exit({port_terminated, Reason})    end.receive_all(Port, Timeout) -> receive_all(Port, Timeout, []).receive_all(Port, Timeout, Buffer) ->    receive        {Port, {data, Data}} -> receive_all(Port, Timeout, [Data | Buffer])        after Timeout -> lists:flatten(lists:reverse(Buffer))    end.

$ erl

Erlang R16B02_basho8 (erts-5.10.3) [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]Eshell V5.10.3  (abort with ^G)1> c(complex1).{ok,complex1}2> complex1:start("go run echo.go").<0.40.0>3> complex1:send("asdhadlsjahdslahjdlhd")."asdhadlsjahdslahjdlhd"4> complex1:send("aksdghjakdsgalkdgaldsagdlkagdlkadg")."aksdghjakdsgalkdgaldsagdlkagdlkadg"


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5560235.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存