Using socket.io with Elm 0.19

Hi everyone! I just wrote an example of a full web application (client and server with build tools etc) that uses an Elm 0.19 client speaking to a Node.js webserver using socket.io-based websockets: https://github.com/matthewsj/elm-socketio

This example is pretty small but demonstrates a bunch of things:

  • A full, small Elm program
  • A way to use ports to expose socket.io functionality to an Elm application
  • A webpack setup that bundles javascript and Elm
  • An easy setup for developing a Elm+Javascript client and a Node.js-based server in one project

I’m not an expert in just about anything in this example, so I’m sure there are a lot of ways to improve it. But hopefully it’s good enough to serve as a starting point for others who want to build similar projects.

Feedback welcome!

7 Likes

Interesting. We use socket.io with a Node.js back end for one small portion of our application as well, and I have been thinking about how we would port that portion of the front end over from jQuery to Elm, and I came to the same conclusion as you—ports is going to be the way to go.

There’s one thing I would add, however. If you will be receiving more than one type of socket.io message (e.g. more than one type of JSON object), then you can make your subscription port take a Json.Encode.Value type rather than a String:

port receiveMessage : (Value -> msg) -> Sub msg

And elsewhere in your code use Json.Decode.oneOf to apply more than one decoder to it. For example, this allows you to use a single port to receive both a Post message and a Reply message (assuming the latter is always nested inside of the former and therefore has a different type in your Elm app).

This approach eliminates the need to litter your Elm app with many similar-but-slightly-different ports / messages to handle all of the incoming websocket message types. The Elm guide does give an example of using a Value in incoming ports, but the concept of a not-yet-decoded JSON value is kind of abstract and might be hard to grok for someone new to Elm.

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.