当前位置:网站首页>一个简单的 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
边栏推荐
猜你喜欢
华为Mux VLAN 二层流量隔离
Priority table and Ascll table
打包项目上传到PyPI
The relationship between base classes and derived classes [inheritance] / polymorphism and virtual functions / [inheritance and polymorphism] abstract classes and simple factories
Mysql索引底层数据结构
Zabbix: PHP option“date.timezone” Fail
Mysql索引优化一
Optisystem应用:光电检测器灵敏度建模
【网络安全】学习笔记 --00
HCIE学习记录——OSI参考模型
随机推荐
SQL在MySQL中是如何执行的
Oauth2.0 security (take WeChat authorized login as an example)
【软件测试】基础篇
The dynamic planning theory
光学好书推荐
OpenPose 运行指令 ([email protected])
光栅区域衍射级数和效率的规范
OpenPose Basic Philosophy
LAMP 环境搭建 yum源安装方式 (Apache 2.4.6 +mysql 8.0.28+php 8.1.3)
使用1D-1D EPE的光波导布局设计工具
hybrid 实现同网段但不同vlan之间通讯
为什么Volatile能保证双重检查锁的线程安全
三大特殊类(String Object 包装类)与异常
【solidity智能合约基础】节约gas的利器--view和pure
炒鸡好用的音乐平台(插件)
Oauth2.0 自定义响应值以及异常处理
项目管理模块-项目权限功能开发
自动化之参数化
Oauth2.0 authentication server construction
tpproxy-tcp透明代理