DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)
  • Everything You Need To Know About Socket.IO
  • Create a Multi-tenancy Application In Nest.js - Part 3
  • Testing WebSocket Endpoints With Firecamp

Trending

  • The Emergence of Cloud-Native Integration Patterns in Modern Enterprises
  • Development of Custom Web Applications Within SAP Business Technology Platform
  • Resistance to Agile Transformations
  • Difference Between High-Level and Low-Level Programming Languages
  1. DZone
  2. Coding
  3. Languages
  4. Handling Websocket Connections in Erlang Application

Handling Websocket Connections in Erlang Application

Check out how to handle websocket connections in an Erlang app, with a look at how to update app dependencies, configuring Cowboy, and more!

Eugene Rudenko user avatar by
Eugene Rudenko
·
Mar. 17, 16 · Tutorial
Like (2)
Save
Tweet
Share
4.88K Views

Join the DZone community and get the full member experience.

Join For Free

Basically, when one needs an Erlang/OTP application to communicate with the World via HTTP or WebSockets it’s really great idea to use Cowboy web server. So, here are a couple of advantages of using it:

  • It’s modular, small but yet powerful. Cowboy includes different basic handlers for HTTP, REST, spdy, and websockets. All you need it just update your application dependencies, configure cowboy, create your own handler “inherited” from basic one.
  • Extremely fast. Cowboy starts custom handler as a separate Erlang process. So if you have a lot of HTTP or websocket connections they will be processed inside Erlang VM concurrently and it’s really awesome! In one of our projects, we have Cowboy handling 50k concurrent websocket connections on single Amazon instance with 4 CPU cores.
  • Can be easily embedded into another Erlang application. And while having selective dispatch and fastCGI support can redirect some requests to PHP, Ruby, and Python applications.

Update Application Dependencies

Here at Oxagile we use rebar as a build tool. Basically, it’s like a composer for PHP applications but much more advanced. So to add cowboy as a dependency we should update our rebar.config file by adding following row into deps section:

{deps, [
  {
    cowboy, 
    ".*",
    {git, "https://github.com/extend/cowboy.git", {tag, "1.0.3"}}
  },

  % other dependencies
  {
    mochijson2,
    ".*",
    {git, "https://github.com/tel/mochijson2.git", {tag, "2.3.2"}}
  },
  {
    amqp_client,
    ".*",
    {git, "git://github.com/jbrisbin/amqp_client.git", {tag, "3.5.2"}}
  }
]}

Then just go to a console and run

$ rebar get deps

Then please update your *_app.src file by adding “cowboy” entry to applications section. Therefore, when you pack your application into release cowboy will be started automatically upon release launch.

{application, demo,
[
 {description, "ws demo app"},
 {vsn, "0.0.1"},
 {registered, []},
 {applications, [
                 kernel,
                 stdlib,
                 inets,
                 cowboy,
                 mnesia
                ]},
 {mod, { demo_app, []}},
 {env, [  ]}
]}.

Configure Cowboy Inside Your Application

Let’s say that our application name is demo. So, you should have demo_app.erl file inside your src folder. Let’s modify it by adding some configuration for Cowboy. First of all, we will configure routing and ports cowboy will listen to.

-module(demo_app).

-behaviour(application).

-export([start/2, stop/1]).

start(_StartType, _StartArgs) ->

 Dispatch = cowboy_router:compile([
   {'_', [
       {"/ws", demo_cowboy_handler_ws, []},
       {"/auth/:token/:user", demo_cowboy_handler_rest, [auth]},
   ]}
 ]),

 {ok, _} = cowboy:start_http(http, 100, [{port, 8889}], [{env, [{dispatch, Dispatch}]}]),
 demo_sup:start_link().


stop(_State) ->
  ok.

In the example above, we’ve added two routes with different handlers which should be implemented and told Cowboy to listen to 8889 port. Also, it’s possible to listen to multiple ports. All you need to do is just call cowboy:start_http multiple times but please note that first parameter of the function (listener name) should be different each time.

start(_StartType, _StartArgs) ->

 DispatchWs = cowboy_router:compile([
   {'_', [
       {"/ws", demo_cowboy_handler_ws, []}
   ]}
 ]),

 DispatchRest = cowboy_router:compile([
   {'_', [
       {"/auth/:token/:user", demo_cowboy_handler_rest, [auth]}
   ]}
 ]),

 {ok, _} = cowboy:start_http(ws, 100, [{port, 8889}], [{env, [{dispatch, DispatchWs}]}]),
 {ok, _} = cowboy:start_http(http, 100, [{port, 8888}], [{env, [{dispatch, DispatchRest}]}]),
 demo_sup:start_link().

Create Your Custom Cowboy Handler

The last thing left to do is just create a handler for websocket connections. It a regular Erlang module but in should be “inherited” from cowboy_websocket_handler. Erlang behaviours are great because they have a well-defined interface: a set of callback functions with custom implementation but with defined input and output. So, for cowboy_websocket_handler these functions are:

init – init websocket connection (see below)
websocket_init – inits state for the ws connection. It’s possible to pass some init parameters through cowboy_router:compile like that:

 DispatchWs = cowboy_router:compile([
   {'_', [
       {"/ws", demo_cowboy_handler_ws, [SomeConfigParams]}
   ]}
 ]),

and 3rd parameter Opts in websocket_init callback will contain these params;
websocket_info – handles Erlang messages. It’s possible to send messages to handler’s process like to any other erlang process i.e. WsPid ! {data, SomeData};
websocket_handle – handles frames received from client;
websocket_terminate – handles termination of ws connection. This function is called just before websocket termination;

Detailed callbacks specification can be found here. So here is the code for our demo handler:

-module(demo_cowboy_handler_ws).

-behaviour(cowboy_websocket_handler).

-export([init/3]).
-export([
   websocket_init/3, websocket_handle/3,
   websocket_info/3, websocket_terminate/3
]).

init({tcp, http}, _Req, _Opts) ->
 {upgrade, protocol, cowboy_websocket}.

websocket_init(_TransportName, Req, Opts) ->
 {ok, Req, undefined_state}.

websocket_handle({text, Msg}, Req, State) ->
 {reply, {text, << "responding to ", Msg/binary >>}, Req, State, hibernate }.

websocket_info({data, SomeData}, Req, State) ->
 {reply, {text, SomeData}, Req, State};
websocket_info(_Info, Req, State) ->
 {ok, Req, State, hibernate}.

websocket_terminate(_Reason, _Req, _State) ->
 ok.

Basically, that’s it with websockets. Cowboy make things much easier and allows us to take care of application logic. For a better understanding of cowboy_websocket_handler behavior please refer to the documentation where you can find a detailed explanation of callback functions’ inputs and outputs. In our opinion, only one small issue exists in Cowboy websocket handler: one can’t terminate (with or without message) WS connection in websocket_init callback, but this can be easily solved by sending Erlang message to WS process and handling it with websocket_info callback.

Kind of Conclusion

Let’s say we have a software solution which includes number of modules implemented using different technologies like in example below:

Handling Websocket Connections in Erlang Application

So, we have WebSocket Clients and PHP App clients (most likely these are 2 parts of one JavaScript application). This application makes HTTP request via 8080 port and uses 8089 port to establish WS connections. In order to handle these connections, we have 2 separate Cowboy handlers created. All other connections are forbidden by the firewall. But, inside our cluster (LAN) we have all the connections allowed. So our internal application can make requests to Cowboy and it’s rest handler which is hidden from the World.

application Connection (dance) WebSocket Erlang (programming language)

Published at DZone with permission of Eugene Rudenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)
  • Everything You Need To Know About Socket.IO
  • Create a Multi-tenancy Application In Nest.js - Part 3
  • Testing WebSocket Endpoints With Firecamp

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: