当前位置:网站首页>一个简单的 erlang 的 udp 服务器和客户端
一个简单的 erlang 的 udp 服务器和客户端
2022-08-02 14:16:00 【freeabc】
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
运行服务器
[email protected]:~/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").运行客户端
[email protected]:~/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边栏推荐
猜你喜欢
随机推荐
创建系统还原点及恢复
idea同时修改相同单词
【无标题】
CDH(computational Diffie-Hellman)问题以及与离散对数、DDH问题的区别
移动端UI自动化相关环境配置
炒鸡好用的音乐平台(插件)
字符数组/字符串数组|数组指针/指针数组/
Mysql索引底层数据结构
固态硬盘到底要不要分区
tcp transparent proxy (IP_TRANSPARENT)
Oauth2.0 resource server construction
VMware 安装openwrt
queue的c实现
Zabbix: PHP option“date.timezone” Fail
【个人向】线性表复习
JOOQ 报错 StackOverflowError
Template Series - Dichotomous
分布式一致性协议-Paxos
Windows下mysql服务无法启动:服务没有报告任何错误。
Xrdp 体验优化









