How to handle properly the `on_session_event`
# ask-ai
a
How to handle properly the
on_session_event
t
Thanks for reaching out, imad. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
The
on_session_event
function in LiveKit is a low-level handler within the Rust SDK that processes session-level events like participant updates, data messages, and connection quality changes. It then forwards these events to higher-level components for further handling. For application developers, the best way to go is to subscribe to the high-level events provided by the client SDKs, like Python or JavaScript. For example: • Python SDK: You can use the
on
method to listen for events such as
participant_connected
or
data_received
. • JavaScript SDK: Try using
room.on(RoomEvent.DataReceived, callback)
to handle events smoothly. If you're diving into SDK development, you might want to take a closer look at
on_session_event
in the Rust SDK files
rtc_engine/mod.rs
and
<http://rtc_session.rs|rtc_session.rs>
. Please feel free to reach out if you'd like help setting up a specific event handler or if you have any other questions—I’m here to help! Sources: livekit-ffi/src/server/requests.rs | livekit-rtc/livekit/rtc/room.py | Events and error handling | LiveKit Docs
a
give me the code
t
I'd love to help you get started with handling events in LiveKit using the Python and JavaScript SDKs. Here are some examples that should make things a bit clearer: Python SDK Example
Copy code
from livekit import rtc

async def on_participant_connected(participant):
    print(f"Participant {participant.identity} connected")

async def on_data_received(data_packet: rtc.DataPacket):
    print(f"Received data: {data_packet.data} from {data_packet.participant}")

# Create a room and register event listeners
room = rtc.Room()
room.on("participant_connected", on_participant_connected)
room.on("data_received", on_data_received)

# Connect to the room
await room.connect("<wss://your-livekit-server>", token)
JavaScript SDK Example
Copy code
import { Room, RoomEvent } from "livekit-client";

const room = new Room();

room.on(RoomEvent.ParticipantConnected, (participant) => {
  console.log(`Participant ${participant.identity} connected`);
});

room.on(RoomEvent.DataReceived, (data, participant) => {
  console.log(`Received data: ${data} from ${participant?.identity}`);
});

// Connect to the room
room.connect("<wss://your-livekit-server>", token);
Just remember to replace
"<wss://your-livekit-server>"
with your actual LiveKit server URL and provide a valid token. If you have any questions or need a hand with anything else, feel free to ask—I’m here to help!