zoukankan      html  css  js  c++  java
  • Erlang练习-UDP

    贴一下代码,例子是从别人那里直接抄来的:

    -module(myudp).
    -export([start/0, client/1]).
    
    %% Server
    start() ->
        spawn(fun() -> server(4000) end).
        
    server(Port) ->
        {ok, Socket} = gen_udp:open(Port, [binary, {active, false}]),
        io:format("server opened socket:~p~n", [Socket]),
        loop(Socket).
        
    loop(Socket) ->
        inet:setopts(Socket, [{active, once}]),
        receive
            {udp, Socket, Host, Port, Bin} ->
                io:format("server received:~p~n", [Bin]),
                gen_udp:send(Socket, Host, Port, Bin),
                loop(Socket)
        end.
        
    %Client code
    client(N) ->
        {ok, Socket} = gen_udp:open(0, [binary]),
        io:format("client opened socket=~p~n", [Socket]),
        ok = gen_udp:send(Socket, "localhost", 4000, N),
        Value = receive
                    {udp, Socket, _, _, Bin} ->
                        io:format("client received:~p~n", [Bin])
                    after 2000 ->
                        0
                    end,
        gen_udp:close(Socket),
        Value.

    尝试运行:

    12> c("myudp").               
    {ok,myudp}
    13> myudp:start().
    server opened socket:#Port<0.2217>
    <0.70.0>
    14> myudp:client("hello").
    client opened socket=#Port<0.2218>
    server received:<<"hello">>
    client received:<<"hello">>
    ok
    15> myudp:client("it's a long story").
    client opened socket=#Port<0.2219>
    server received:<<"it's a long story">>
    client received:<<"it's a long story">>
    ok
    16> myudp:client(<<"nothing">>).      
    client opened socket=#Port<0.2220>
    server received:<<"nothing">>
    client received:<<"nothing">>
    ok

    话说,上面的直接使用引号的输入,和使用引号再使用尖括号的输入,效果是一样的。。。使用两个尖括号是什么?好像是在二进制的集合那里看到过这个符号??

  • 相关阅读:
    Python异常处理
    python抽象类
    python传参*和**的区别
    python 多重继承构造函数调用顺序
    linux 自启动 | 三种方式自启动
    Linux 项目 shell 自动获取报告本机IP (1) | 通过shell 自动获取报告本机IP
    Go 基础学习笔记 (5)| 数据类型说明与使用
    GO 基础学习笔记(4)| 参数传递
    生活问题 | 对华为畅玩手机5X进行升级
    markdown 语法
  • 原文地址:https://www.cnblogs.com/pied/p/3790087.html
Copyright © 2011-2022 走看看