当前位置:网站首页>一个简单的 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
边栏推荐
- WEB自动化之多窗口操作、切换frame、弹窗处理
- 许多代码……
- The relationship between base classes and derived classes [inheritance] / polymorphism and virtual functions / [inheritance and polymorphism] abstract classes and simple factories
- Run ns3 with multiple processes
- OpenPose 基本理念
- Mysql索引底层数据结构
- HCIE学习记录——OSI参考模型
- The use of a semaphore/interprocess communication 】 【 Shared memory
- JCMsuite应用:四分之一波片
- implement tcp bbr on ns3 (在ns3上实现TCP BBR)
猜你喜欢
随机推荐
光导布局设计工具
Xshell 使用删除键乱码问题
抽象类和接口 基本知识点复习
华为单臂路由配置,实现不同vlan之间的通信
【网络安全】学习笔记 --00
Three-way joint interface data security issues
Google AdSense注册流程
大厂年薪50w+招聘具有测试平台开发能力的测试工程师
Apache ShardingSphere 5.1.1 正式发布
软件测试之WEB自动化
The relationship between base classes and derived classes [inheritance] / polymorphism and virtual functions / [inheritance and polymorphism] abstract classes and simple factories
VMware 安装openwrt
unittest框架
关于导出聊天记录这件事……
PostgreSQL 协议数据样例
char array/string array|array pointer/pointer array/
使用三个线程,按顺序打印X,Y,Z,连续打印10次
ssm整合
Template Series - Dichotomous
Evaluate multipath BBR congestion control on ns3