0

I'm coding a simple chat room using WebSocket, Javascript (client), and Python (server). I read a few tutorials and documentations, and here are my two questions.

1) On the JS side, is it normal that I have to do things like:

ws.send(JSON.stringify({ "type" : "message", "message" : "Hello" }));
ws.send(JSON.stringify({ "type" : "username_change", "newusername" : "John" }));

?

Isn't there something "less low-level" like ws.emit('message', 'hello') or ws.emit('username_change', 'John') ?

2) On the server side (using Python + Bottle framework) is it standard to have:

users = set()

@get('/websocket', apply=[websocket])
def chat(ws):
    users.add(ws)
    while True:
        msg = ws.receive()
        for u in users:
            u.send(msg)
    users.remove(ws)

I find it quite low-level again to have to maintain a list of users myself, as well as the fact of sending messages one by one to all users with a for loop. I thought there was a .broadcast() function that allows to send a message automatically to all connected users.

Am I missing something in the Websocket-landscape?

Basj
  • 41,386
  • 99
  • 383
  • 673
  • 1
    The higher level interface you are asking about would be socket.io which is a layer on top of webSocket. – jfriend00 Oct 29 '16 at 00:21
  • Ok thanks @jfriend00. Does socket.io loop over all connected users when we use broadcast ? or does it use a better / more efficient method ? – Basj Oct 29 '16 at 10:25
  • It loops. There is no more efficient method for broadcasting to webSocket connections. Each webSocket connection is its own TCP socket. You have to send separately to each one. That's just how TCP works. – jfriend00 Oct 29 '16 at 15:02
  • Ok thanks @jfriend00 . If you post it as an answer, I'll accept it! – Basj Oct 29 '16 at 15:20

1 Answers1

1

socket.io is a higher level interface built on top of webSockets. It offers many additional features, but foremost among them is a message passing scheme where you can do this to send data:

socket.emit("someMsg", someData);

And, this to receive:

socket.on("someMsg", function(data) {
    // process incoming data here
});

Here's a partial list of features socket.io adds on top of a webSocket: Moving from socket.io to raw websockets?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979