Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How build non-blocking TCP server with ssl encryption

Non-blocking TCP server on trapexit.org explains how to build server based on tcp_gen, but i want to modify this example and make it work with ssl. For now i have completely no idea how to replace

{ok, Ref} = prim_inet:async_accept(Listen_socket, -1)
like image 514
JLarky Avatar asked Mar 01 '23 07:03

JLarky


1 Answers

simple echo_ssl with multi threading

-module(echo_ssl).
-compile([export_all]).

main() ->
    application:start(crypto),
    application:start(ssl),
    ssl:seed("TODO random here"),
    {ok, ListenSocket} = ssl:listen(2840, [
        {ssl_imp, new},
        {active, false},
        {verify, 0},
        {mode,binary},
        {cacertfile, "certs/etc/server/cacerts.pem"},
        {certfile, "certs/etc/server/cert.pem"},
        {keyfile, "certs/etc/server/key.pem"}
    ]),
    io:format("ready to accept connections at port 2840 ~p\n", [ListenSocket]),
    server_loop(ListenSocket).

server_loop(ListenSocket) ->
    {ok, Socket} = ssl:transport_accept(ListenSocket),
    io:format("accepted connection from ~p\n", [ssl:peername(Socket)]),
    ssl:ssl_accept(Socket),
    spawn(fun() -> loop(Socket) end),
    server_loop(ListenSocket).

loop(Socket) ->
    io:format("waiting for packet~n"),
    case ssl:recv(Socket, 1000, 2000) of
        {ok, Data} ->
            io:format("received data: ~s~n", [binary_to_list(Data)]),
            Return = ssl:send(Socket, Data),
            io:format("sending ~p~n", [Return]),
            loop(Socket);
        {error, timeout} ->
           loop(Socket);
        Else ->
            io:format("crap ~p~n",[Else])
    end.
like image 153
mog Avatar answered Mar 07 '23 09:03

mog