欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

erlang分布式入门(三)-TCP Server-Client

程序员文章站 2022-06-14 16:16:14
...

直接上代码吧!

 

1.服务端:tcp_server.erl

-module(tcp_server).
-author('Jesse E.I. Farmer <jesse@20bits.com>').
-export([listen/1]).

-define(TCP_OPTIONS, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]).

% Call echo:listen(Port) to start the service.
listen(Port) ->
    {ok, LSocket} = gen_tcp:listen(Port, ?TCP_OPTIONS),
    accept(LSocket).

% Wait for incoming connections and spawn the echo loop when we get one.
accept(LSocket) ->
    {ok, Socket} = gen_tcp:accept(LSocket),
    spawn(fun() -> loop(Socket) end),
    accept(LSocket).

% Echo back whatever data we receive on Socket.
loop(Socket) ->
    case gen_tcp:recv(Socket, 0) of
        {ok, Data} ->
            io:format("recv ~p~n", [Data]),
            gen_tcp:send(Socket, Data),
            loop(Socket);
        {error, closed} ->
            ok
    end.

 

2.客户端:tcp_client.erl

-module(tcp_client).
-export([start/1, send_data/2, close/1]).

start(Port) ->
        {ok, Socket} = gen_tcp:connect("127.0.0.1", Port, [binary, {packet, raw}, {active, true}, {reuseaddr, true}]),
        Socket.


send_data(Socket, Data) when is_list(Data) orelse is_binary(Data) ->
        gen_tcp:send(Socket, Data),
        receive
                {tcp, Socket, Bin} ->
                        io:format("recv ~p~n", [Bin]);
                {tcp_closed, Socket} ->
                        io:format("remote server closed!~n")
        end.

close(Socket) when is_port(Socket) ->
        gen_tcp:close(Socket).

 

3.测试运行,需要开启两个终端,一个运行tcp_server,一个运行tcp_client,先运行tcp_server

[root@centos-183 erlang-learn]# erl
Erlang R15B (erts-5.9) [source] [smp:2:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9  (abort with ^G)
1> c(tcp_server).
{ok,tcp_server}
2> tcp_server:listen(8080).
recv <<"abc">>

 

在tcp_client端

[root@centos-183 erlang-learn]# erl
Erlang R15B (erts-5.9) [source] [smp:2:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9  (abort with ^G)
1> c(tcp_client).
{ok,tcp_client}
2> Socket=tcp_client:start(8080).
#Port<0.2242>
3> tcp_client:send_data(Socket,<<"abc">>). 
recv <<"abc">>
ok
4> 
 

 

  • erlang分布式入门(三)-TCP Server-Client
            
    
    博客分类: Erlang erlangtcpserverclient 
  • 大小: 31.8 KB