I have just started learning about websockets so if something I say doesn't make sense that is probably why. I understand the very basics of how they work. A client can send a message to the server and vice versa. My question is what if you want the client to be able to use the same connection for different purposes. For example, what if the client can send a message or move their character in a game. Would you need separate sockets to handle these cases? I imagine that you could just create a standard for your messages and then have a switch statement on the server, but that seems inelegant. If it matters I am using Node's "express-ws" package for the server. Thanks for the help!
1 Answers
Your intuition is correct. You would typically construct a standard message format that has a property that indicates the message type.
You don't have to use a switch statement on the server. If you want, you could create an eventEmitter and just .emit()
each incoming message to an eventName the same as the message type. Then, your server code would just register listeners for whatever messages it wants to listen for and you'd avoid the switch statement. This would also allow your server code to be more compartmentalized in modules. You'd just have to share the eventEmitter which any module that wishes to listen for an incoming message or send an outgoing message.
FYI, socket.io is a client and server layer that sits on top of webSocket and does all this for you (along with a number of other features). There's a partial list of features socket.io has here: Moving from socket.io to raw websockets?

- 683,504
- 96
- 985
- 979