A Small Note on WebSockets: Objects

I wanted to make a note about this because I’ve been working a bit with WebSockets. I ran into a little bit of a question that I didn’t see a great answer for online. That usually means one of two things:

  1. Maybe I didn’t look very hard.
  2. Maybe I’m a fool and it’s so obvious that nobody needed to ask.

Just in case neither of those are true, or maybe you’re as big a fool as I am, here’s the situation.

Objects

I wanted to send some data around on the WebSocket connection I had open, but I really didn’t want to mess around with specifically formatted strings. That would be madness. I really wanted to shove an object through the connection, as it happens.

This is where I worry that the solution might be obvious. I was overthinking it like mad, trying to figure out if there was some way that I’d have to come up with a custom way to parse a string and tease an object from it.

I should’ve probably just written that statement because it really makes the solution obvious. Check it out:

const myFancyObject = {
    msg: "Put whatever makes your heart sing right here.",
    xCoord: outOfScope.offsetX,
    yCoord: outOfScope.offsetY
};

const theMissingLink = JSON.stringify(myFancyObject);
webSocketConnection.send(theMissingLink);

There are a few assumptions in that code because I didn’t think you needed an entire file to illustrate the interesting part. Imagine that a variable named outOfScope exists somewhere and that you’ve established a WebSockets connection in the aptly-named “webSocketConnection.”

On the other end, wherever your server is located, you’ll have to parse out that string (theMissingLink in the example above) into something your language of choice can work with. In my case, for instance, it was Node, and I simply invoked JSON.parse() on that end.

Obvious?

Maybe! I’m not embarrassed to state obvious things, though. Someone might be having the same trouble I was; I’d like to save that someone some time. Plus, having this information available in multiple spots makes it more likely that it sticks around.

I may have more WebSockets information coming as I muddle through a personal project. In the interim, let me know if there are any questions that you have and I’ll see if I can derive a solution for you!

Published by Joe

I'm a software developer from Minnesota. I also ride bikes!

Leave a comment