1. 服务器端代码如下:
-module(server).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-export([start/0]).
-record(state, {socket,
port,
local_ip,
broad_ip}).
%% External interface:
start() ->
io:format("start~n"),
{ok, Server} = gen_server:start_link({local,?MODULE}, ?MODULE, [], []),
io:format("Server: ~w~n", [Server]).
%%Internal server methods:
init([]) ->
Port = 15000,
{ok, Socket} = gen_udp:open(Port, [binary,
{active, true},
{reuseaddr, true}]),
{ok, #state{socket = Socket, port = Port}}.
handle_cast(process_msg, State) ->
{noreply, State}.
handle_call(_Request, _From, State) ->
{noreply, State}.
handle_info({udp, Socket, IP, InPortNo, Packet}, #state{socket=Socket}) ->
io:format("whooopie, ip ~p, port ~p, got a packet ~p~n", [IP, InPortNo, Packet]),
{noreply, #state{socket=Socket}}.
terminate(_Reason, #state{socket = LSocket}) ->
gen_udp:close(LSocket).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
active 一定设置为 true
运行服务器
freeabc@ubuntu:~/test$ erl
Erlang/OTP 22 [erts-10.6.4] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]
Eshell V10.6.4 (abort with ^G)
1> c(server).
{ok,server}
2>
2>
2>
2> server:start().
start
Server: <0.85.0>
ok
whooopie, ip {127,0,0,1}, port 40263, got a packet <<"hello">>
whooopie, ip {127,0,0,1}, port 38798, got a packet <<"hello">>
3>
2. 客户端代码?
-module(client).
-export([start/0]).
start() ->
Port = 15000,
{ok, Socket} = gen_udp:open(0, [binary, {active, false}]),
gen_udp:send(Socket, "localhost", Port, "hello").
运行客户端
freeabc@ubuntu:~/test$ erl
Erlang/OTP 22 [erts-10.6.4] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]
Eshell V10.6.4 (abort with ^G)
1> c(client).
{ok,client}
2>
2> client:start().
ok
3> client:start().
ok
|