开发者

Looking for a simple ssl erlang example

In the book Erlang Programming one of the exercises proposed was to print on screen the request coming from a browser using gen_tcp. I made it for http requests as follows:

-module(tcp).
-export([server/0, wait_connect/2]).

server() ->
    {ok, ListenSocket} = gen_tcp:listen(1234, [binary, {active, f开发者_运维问答alse}]),
    wait_connect(ListenSocket,0).

wait_connect(ListenSocket, Count) ->
    {ok, Socket} = gen_tcp:accept(ListenSocket),
    spawn(?MODULE, wait_connect, [ListenSocket, Count+1]),
    get_request(Socket, [], Count).

get_request(Socket, BinaryList, Count) ->
    Request = gen_tcp:recv(Socket, 0),
    io:format("~p~n", [Request]).

Now I am wondering how this can be done in case of https request. Can you provide a very simple example, or point me to some resource on books or online?


Here is the user guide for Erlang SSL application: Erlang -- SSL User Guide

The guide contains also, in the API chapter, a paragraph on updating existing connections to SSL.

Regarding your code, you should do something like:

  • on server and client side you have to issue: ssl:start()
  • server side: handshake SSL (remember to set 'active' to false for the listening socket)

    {ok, SSLSocket} = ssl:ssl_accept(Socket, [{cacertfile, "cacerts.pem"}, {certfile, "cert.pem"}, {keyfile, "key.pem"}]).

    where "cacerts.pem", "cert.pem", "key.pem" are files related to SSL certification

  • client side: upgrade connection to SSL: {ok, SSLSocket} = ssl:connect(Socket, [{cacertfile, "cacerts.pem"}, {certfile, "cert.pem"}, {keyfile, "key.pem"}], infinity).

As per documentation, now SSLSocket is a ssl channel that can be used to send messages like: ssl:send(SSLSocket, "foo").

Hope this helps!


I would suggest to read the following article about SSL sockets in Erang that contains complete code of the SSL echo server and client.

Erlang SSL sockets example - ssl server & client)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜