Reputation: 46513
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?
Upvotes: 1
Views: 385
Reputation: 707486
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?
Upvotes: 1