Socket Io Room

0 views
Skip to first unread message

Giulia Satmary

unread,
Aug 3, 2024, 5:26:38 PM8/3/24
to taportani

I am trying to make a logged in user to join a certain socket.io room on connect. According to any examples I found on the net I seem to have emit some action from client to be able to join some room. Something like:

In the example above, a room is created with a name specified in variable room. You don't need to store this room object anywhere, because it's already part of the io object. You can then treat the room like its own socket instance.

Within each namespace, you can also define arbitrary channels that sockets can join and leave. These channels are called rooms. Rooms are used to further-separate concerns. Rooms also share the same socket connection like namespaces. One thing to keep in mind while using rooms is that they can only be joined on the server side.

Can I extend the master socket into another room (office) running a RJ11 cable and wiring the front of the Master Socket 5C to another one in the office, and thus, connect the router in the office, rather than the living room.

Just wire from the data extension terminals as shown in the last picture on the document you posted. If you want telephony as well as data, fit an extension phone socket and use a plug in filter at the office or if just data, fit an RJ11 socket.

I had written a event recorder and event player socket which extends base socket. Event recorder records time and message sent - all this is persisted in a json file. Event player socket will replay the messages with exact timing when it is initialised. We use this for testing, debugging and replaying player sessions.

The entire series will be building on one repository that has both the server and the client for the application, so for each part you can download the repository from specific commits to follow along or you can clone the entire repository in it's finished state.

A lot of these class methods are pretty straightforward and are in one way or another doing sorts of getters, setters, or directly mutating the rooms array which stores all active rooms on the server.

Our login page has both a form to create and join a new room, and also to select from existing rooms that have been created. To store an existing room selection we make use of a simple useState hook from React.

Whenever a user creates or joins an existing room, or if a user attempts to come to the login page while already being logged in and in an existing room - we need to direct them over to the Chat page.

Rooms are a tool in socket.io servers for keeping track of groups of connected users. You can then iterate the sockets in a room or broadcast to all of them. There's really nothing more to them than that. The server can put a socket into a room or remove one from a room. When a socket disconnects, it is automatically removed from all rooms it is in.

Your scheme for using only messages and then letting each client decide which messages to listen to is a client-driven scheme (client decides which messages to pay attention to) as opposed to a server-driven scheme and it probably doesn't scale as well because it requires you to send all messages to all clients so that all clients have a chance to listen to them all. Rooms, on the other hand, are a server-driven scheme where the server keeps track (in advance) of which sockets are in which group and only sends messages to the clients that should get those messages. The server both controls things and does it more efficiently.

Plus, in some cases, you can't leave it up to the client to decide what it's allowed to listen to. Imagine you have a chat server that sets up private 1-on-1 chat sessions. In that case, you can't have any circumstance where clientA is allowed to listen in on chat messages for some other chat session. To enforce that, the server has to ONLY send chat messages to the pairwise participants. This is a feature that rooms would be very useful for and your scheme would not.

Instructions are at the link above. You want to subclass
StreamRequestHandler and have your .handle method record the client
socket in the_client_sockets, which you need to create. (An empty global
list or set would do.)

The init_app() style of initialization is also supported. To start theweb server simply execute your script. Note the way the web server is started.The socketio.run() function encapsulates the start up of the web server andreplaces the app.run() standard Flask development server start up. When theapplication is in debug mode the Werkzeug development server is still used andconfigured properly inside socketio.run(). In production mode the eventletweb server is used if available, else the gevent web server is used. Ifeventlet and gevent are not installed, the Werkzeug development web server isused.

The flask run command introduced in Flask 0.11 can be used to start aFlask-SocketIO development server based on Werkzeug, but this method of startingthe Flask-SocketIO server is not recommended due to lack of WebSocket support.Previous versions of this package included a customized version of theflask run command that allowed the use of WebSocket on eventlet and geventproduction servers, but this functionality has been discontinued in favor of thesocketio.run(app) startup method shown above which is more robust.

When using SocketIO, messages are received by both parties as events. On theclient side Javascript callbacks are used. With Flask-SocketIO the serverneeds to register handlers for these events, similarly to how routes arehandled by view functions.

When the name of the event is a valid Python identifier that does not collidewith other defined symbols, the @socketio.event decorator provides a morecompact syntax that takes the event name from the decorated function:

Named events are the most flexible, as they eliminate the need to includeadditional metadata to describe the message type. The names message,json, connect and disconnect are reserved and cannot be used fornamed events.

Clients may request an acknowledgement callback that confirms receipt of amessage they sent. Any values returned from the handler function will bepassed to the client as arguments in the callback function:

In the above example, the client callback function will be invoked withtwo arguments, 'one' and 2. If a handler function does not return anyvalues, the client callback function will be invoked without arguments.

When using callbacks, the Javascript client receives a callback function toinvoke upon receipt of the message. After the client application invokes thecallback function the server invokes the corresponding server-side callback.If the client-side callback is invoked with arguments, these are provided asarguments to the server-side callback as well.

When a message is sent with the broadcast option enabled, all clientsconnected to the namespace receive it, including the sender. When namespacesare not used, the clients connected to the global namespace receive themessage. Note that callbacks are not invoked for broadcast messages.

In all the examples shown until this point the server responds to an eventsent by the client. But for some applications, the server needs to be theoriginator of a message. This can be useful to send notifications to clientsof events that originated in the server, for example in a background thread.The socketio.send() and socketio.emit() methods can be used tobroadcast to all connected clients:

Note that socketio.send() and socketio.emit() are not the samefunctions as the context-aware send() and emit(). Also note that in theabove usage there is no client context, so broadcast=True is assumed anddoes not need to be specified.

For many applications it is necessary to group users into subsets that can beaddressed together. The best example is a chat application with multiple rooms,where users receive messages from the room or rooms they are in, but not fromother rooms where other users are. Flask-SocketIO supports this concept ofrooms through the join_room() and leave_room() functions:

All clients are assigned a room when they connect, named with the session IDof the connection, which can be obtained from request.sid. A given clientcan join any rooms, which can be given any names. When a client disconnects itis removed from all the rooms it was in. The context-free socketio.send()and socketio.emit() functions also accept a to argument to broadcastto all clients in a room.

The auth argument in the connection handler is optional. The client canuse it to pass authentication data such as tokens in dictionary format. If theclient does not provide authentication details, then this argument is set toNone. If the server defines a connection event handler without thisargument, then any authentication data passed by the client is discarded.

The connection event handler can return False to reject the connection, orit can also raise ConnectionRefusedError. This is so that the client can beauthenticated at this point. When using the exception, any arguments passed tothe exception are returned to the client in the error packet. Examples:

As an alternative to the decorator-based event handlers described above, theevent handlers that belong to a namespace can be created as methods of aclass. The flask_socketio.Namespace is provided as a base class tocreate class-based namespaces:

When class-based namespaces are used, any events received by the server aredispatched to a method named as the event name with the on_ prefix. Forexample, event my_event will be handled by a method named on_my_event.If an event is received for which there is no corresponding method defined inthe namespace class, then the event is ignored. All event names used inclass-based namespaces must use characters that are legal in method names.

As a convenience to methods defined in a class-based namespace, the namespaceinstance includes versions of several of the methods in theflask_socketio.SocketIO class that default to the proper namespacewhen the namespace argument is not given.

Socket.io is an easy-to-use JavaScript library for enabling WebSocket connections. WebSocket is a computer communications protocol that provides two-way, or full-duplex, communication channels over a single TCP connection.

c80f0f1006
Reply all
Reply to author
Forward
0 new messages