Para apps
Una API WebSocket sin servidor que mantener
Una API de tiempo real sobre WebSockets alojados, para Next.js, Laravel, Django y cualquier otro stack. Tu servidor envía un evento en una petición corta y cada página de la sala lo recibe al instante. Nosotros mantenemos las conexiones abiertas, así que no hay ningún servidor WebSocket que ejecutar, escalar o reiniciar.
O prueba la demo en vivo: una tienda pequeña, donde un pedido pasa a enviado en otra ventana a medida que haces clic.
Los mejores precios para WebSockets. Desde $11.99 al mes por 1000 conexiones simultáneas, con facturación anual, o $14.99 con facturación mensual.
Next.js en el servidor y React en la página.
'use server';
import { realtime } from '@/lib/realtime';
export async function markShipped( id: string ) {
await saveStatus( id, 'shipped' );
await realtime.to( `order:${ id }` )
.emit( 'updated', { status: 'shipped' } );
}app.post( '/orders/:id/ship', async ( req, res ) => {
await saveStatus( req.params.id, 'shipped' );
await realtime.to( `order:${ req.params.id }` )
.emit( 'updated', { status: 'shipped' } );
res.json( { ok: true } );
} );import { createServer } from 'node:http';
const routes = realtime.node( userOf );
createServer( async ( req, res ) => {
if ( req.url.startsWith( '/api/realtime/' ) ) {
return routes( req, res );
}
await saveStatus( '1042', 'shipped' );
await realtime.to( 'order:1042' )
.emit( 'updated', { status: 'shipped' } );
res.end( 'ok' );
} ).listen( 3000 );public function ship( Order $order )
{
$order->update( [ 'status' => 'shipped' ] );
// Your event, as for any broadcaster.
broadcast( new OrderUpdated( $order ) );
}save_status( $id, 'shipped' );
$realtime->to( "order:{$id}" )
->emit( 'updated', [ 'status' => 'shipped' ] );from django.db import transaction
from wordplus_realtime.django import realtime
order.status = "shipped"
order.save()
# Once it commits, so nobody sees a change rolled back.
transaction.on_commit(lambda: realtime.to(f"order:{order.pk}")
.emit("updated", {"status": order.status}))@app.post("/orders/{pk}/ship")
async def ship(pk: int):
await save_status(pk, "shipped")
await realtime.to(f"order:{pk}").aemit(
"updated", {"status": "shipped"}
)
return {"ok": True}@app.post("/orders/<int:pk>/ship")
def ship(pk):
save_status(pk, "shipped")
realtime.to(f"order:{pk}").emit(
"updated", {"status": "shipped"}
)
return {"ok": True}# A signed JSON request, from any language.
# wordplus is a signed curl, on the signing page of the docs.
wordplus POST /wordplus/realtime/emit '{
"rooms": ["order:1042"],
"event": "updated",
"data": {"status": "shipped"}
}'Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const rt = await connect();
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import { connect } from '@wordplus/realtime';
const settings = await fetch( '/api/realtime/config' );
const rt = await connect( await settings.json() );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );import Echo from 'laravel-echo';
import { WordplusConnector } from '@wordplus/realtime/echo';
window.Echo = new Echo( {
broadcaster: WordplusConnector,
...window.wordplusRealtimeConfig,
} );
window.Echo.private( 'order:1042' )
.listen( '.updated', ( data ) => showStatus( data.status ) );'use client'; // in Next.js
import { useState } from 'react';
import { useRoom } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Status( { id, initial } ) {
const [ status, setStatus ] = useState( initial );
useRoom( `order:${ id }`, {
updated: ( data ) => setStatus( data.status ),
} );
return <p>{ status }</p>;
}<script setup>
import { ref } from 'vue';
import { useRoom } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const props = defineProps( [ 'id', 'initial' ] );
const status = ref( props.initial );
useRoom( () => `order:${ props.id }`, {
updated: ( data ) => { status.value = data.status; },
} );
</script>
<template>
<p>{{ status }}</p>
</template><script>
import { useRoom } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
let { id } = $props();
let status = $state( 'new' );
useRoom( () => `order:${ id }`, {
updated: ( data ) => { status = data.status; },
} );
</script>
<p>{ status }</p>import { Component, Input, signal } from '@angular/core';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
@Component( {
selector: 'app-status',
template: '<p>{{ status() }}</p>',
} )
export class StatusComponent {
@Input( { required: true } ) id!: number;
status = signal( 'new' );
async ngOnInit() {
const rt = await realtime;
rt.join( `order:${ this.id }` ).on( 'updated', ( data ) => {
this.status.set( data.status );
} );
}
async ngOnDestroy() {
( await realtime ).leave( `order:${ this.id }` );
}
}import WordPlusRealtime
let rt = Realtime(RealtimeOptions(
app: "s1500000007",
endpoint: URL(string: "https://shop.example.com/api/realtime")!,
headers: { ["Authorization": "Bearer \(session.token)"] }
))
rt.connect()
let order = rt.join("order:1042")
order.on("updated") { data, _ in
showStatus(data["status"]?.string ?? "")
}import cloud.wordplus.realtime.*
import kotlinx.serialization.json.*
val rt = Realtime(RealtimeOptions(
app = "s1500000007",
endpoint = "https://shop.example.com/api/realtime",
headers = {
mapOf("Authorization" to "Bearer ${session.token}")
},
))
rt.connect()
val order = rt.join("order:1042")
order.on("updated") { data, _ ->
val status = data.jsonObject["status"]?.jsonPrimitive?.content
showStatus(status ?: "")
}// First in index.js, which sealing needs:
// import 'react-native-get-random-values';
import { useState } from 'react';
import { Text } from 'react-native';
import { RealtimeProvider, useRoom } from '@wordplus/realtime/react';
const options = {
app: 's1500000007',
endpoint: 'https://app.example.com/api/realtime',
headers: { Authorization: 'Bearer ' + session.token },
};
export const App = () => (
<RealtimeProvider options={ options }>
<Status id={ 1042 } initial="new" />
</RealtimeProvider>
);
function Status( { id, initial } ) {
const [ status, setStatus ] = useState( initial );
useRoom( `order:${ id }`, {
updated: ( data ) => setStatus( data.status ),
} );
return <Text>{ status }</Text>;
}import 'package:wordplus_realtime/wordplus_realtime.dart';
final rt = await WordPlusRealtime.connect(
app: 's1500000007',
endpoint: 'https://app.example.com/api/realtime',
headers: {'Authorization': 'Bearer ${session.token}'},
);
final order = rt.join('order:1042');
order.on('updated', (data, _) => showStatus(data['status']));
Alojado
La parte que ya no tienes que mantener
Un servidor WebSocket funciona en tu portátil. En producción tiene que mantener cada conexión abierta durante horas, compartir cada evento entre máquinas y sobrevivir a tus despliegues, y un host serverless no puede mantener ninguna conexión. Aquí las conexiones se quedan con nosotros y tu servidor sigue como está.
Tu servidor envía una petición
- Next.js, Express, Node.js, Laravel, PHP, Django, FastAPI, Flask
- Funciones serverless y edge
- Cualquier otro stack
Tus usuarios siguen conectados
- Pestañas del navegador
- Apps móviles
- Eventos en tiempo real
- Salas
- Presencia
- Reconexiones
Sin servidores de websockets que mantener
Tu propio servidor de websockets tiene que mantener cada conexión, crecer más allá de una máquina y seguir en pie durante los despliegues. La nube lo hace, sumando servidores a medida que crece tu tráfico, y una página pasa a otro servidor sin cortes.
Cualquier host para tu servidor
Tu servidor solo firma y envía, así que funciona en cualquier sitio, también en funciones serverless y edge, que por sí mismas no pueden mantener una conexión abierta.
Tu inicio de sesión sigue siendo tuyo
Un usuario es el id con el que tu app lo conoce, leído en tu propio servidor, así que tu sesión y tus cookies funcionan como ahora.
Tu servidor decide
Envía a quien quieras, mira quién está en línea y gestiona tus salas
Una sala es solo un nombre, como chat:7, sin nada que crear en la nube. Tu base de datos dice qué salas existen y quién está en ellas, una regla de tu servidor la lee y la nube obliga a cada página a respetar la respuesta. Aquí tienes un chat de equipo, de principio a fin.
Next.js en el servidor y React en la página.
Crear una sala
Guárdala en tu base de datos y escribe una regla que la lea. La regla se ejecuta cuando alguien pide unirse: false lo deja fuera, true lo deja entrar y readOnly le permite leer pero no enviar nada. Aquí db es tu propia base de datos y me es la persona que ha iniciado sesión.
// A room is a row of yours. Nothing is created in the cloud.
const room = await db.room.create( { data: { name: 'Team' } } );
await db.member.create( { data: { roomId: room.id, userId: me, role: 'member' } } );
// Its name is yours to choose: row 7 is the room chat:7.// Once, for every chat. When someone asks to join chat:7, id is '7'.
realtime.room( 'chat:{id}', async ( user, { id } ) => {
const room = await db.room.findUnique( { where: { id: Number( id ) } } );
if ( !room || room.closed ) return false; // no such room, or closed
const member = await db.member.findFirst( { where: { roomId: room.id, userId: user } } );
if ( !member || member.banned ) return false; // not a member, or banned
return member.role === 'reader' ? { readOnly: true } : true;
}, { presence: true, emit: [ 'message' ] } );// A room is a row of yours. Nothing is created in the cloud.
const room = await db.room.create( { data: { name: 'Team' } } );
await db.member.create( { data: { roomId: room.id, userId: req.session.userId, role: 'member' } } );
// Its name is yours to choose: row 7 is the room chat:7.// Once, for every chat. When someone asks to join chat:7, id is '7'.
realtime.room( 'chat:{id}', async ( user, { id } ) => {
const room = await db.room.findUnique( { where: { id: Number( id ) } } );
if ( !room || room.closed ) return false; // no such room, or closed
const member = await db.member.findFirst( { where: { roomId: room.id, userId: user } } );
if ( !member || member.banned ) return false; // not a member, or banned
return member.role === 'reader' ? { readOnly: true } : true;
}, { presence: true, emit: [ 'message' ] } );// A room is a row of yours. Nothing is created in the cloud.
const room = await db.room.create( { data: { name: 'Team' } } );
await db.member.create( { data: { roomId: room.id, userId: me, role: 'member' } } );
// Its name is yours to choose: row 7 is the room chat:7.// Once, for every chat. When someone asks to join chat:7, id is '7'.
realtime.room( 'chat:{id}', async ( user, { id } ) => {
const room = await db.room.findUnique( { where: { id: Number( id ) } } );
if ( !room || room.closed ) return false; // no such room, or closed
const member = await db.member.findFirst( { where: { roomId: room.id, userId: user } } );
if ( !member || member.banned ) return false; // not a member, or banned
return member.role === 'reader' ? { readOnly: true } : true;
}, { presence: true, emit: [ 'message' ] } );// A room is a row of yours. Nothing is created in the cloud.
$room = Room::create( [ 'name' => 'Team' ] );
$room->members()->create( [ 'user_id' => auth()->id(), 'role' => 'member' ] );
// Its name is yours to choose: row 7 is the room chat:7.// Once, for every chat. When someone asks to join chat:7, $p['id'] is '7'.
$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
$realtime->room( 'chat:{id}', function ( $user, array $p ) {
$room = Room::find( $p['id'] );
if ( ! $room || $room->closed ) {
return false; // no such room, or closed
}
$member = $room->members()->where( 'user_id', $user )->first();
if ( ! $member || $member->banned ) {
return false; // not a member, or banned
}
return $member->role === 'reader' ? [ 'readOnly' => true ] : true;
}, [ 'presence' => true, 'emit' => [ 'message' ] ] );
} );// A room is a row of yours. Nothing is created in the cloud.
$db->prepare( 'INSERT INTO rooms (name) VALUES (?)' )->execute( [ 'Team' ] );
$room = $db->lastInsertId();
$db->prepare( 'INSERT INTO members (room_id, user_id, role) VALUES (?, ?, ?)' )
->execute( [ $room, $_SESSION['user_id'], 'member' ] );
// Its name is yours to choose: row 7 is the room chat:7.// Once, for every chat. When someone asks to join chat:7, $p['id'] is '7'.
$realtime->room( 'chat:{id}', function ( $user, array $p ) use ( $db ) {
$query = $db->prepare( 'SELECT closed FROM rooms WHERE id = ?' );
$query->execute( [ $p['id'] ] );
$room = $query->fetch();
if ( ! $room || $room['closed'] ) {
return false; // no such room, or closed
}
$query = $db->prepare( 'SELECT role, banned FROM members WHERE room_id = ? AND user_id = ?' );
$query->execute( [ $p['id'], $user ] );
$member = $query->fetch();
if ( ! $member || $member['banned'] ) {
return false; // not a member, or banned
}
return $member['role'] === 'reader' ? [ 'readOnly' => true ] : true;
}, [ 'presence' => true, 'emit' => [ 'message' ] ] );# A room is a row of yours. Nothing is created in the cloud.
room = Room.objects.create(name="Team")
room.members.create(user=request.user, role="member")
# Its name is yours to choose: row 7 is the room chat:7.# Once, for every chat. When someone asks to join chat:7, p["id"] is "7".
def may_join_chat(user, p):
room = Room.objects.filter(pk=p["id"]).first()
if room is None or room.closed:
return False # no such room, or closed
member = room.members.filter(user_id=user).first()
if member is None or member.banned:
return False # not a member, or banned
return {"readOnly": True} if member.role == "reader" else True
realtime.room("chat:{id}", may_join_chat, presence=True, emit=["message"])# A room is a row of yours. Nothing is created in the cloud.
room = Room(name="Team", members=[Member(user_id=me, role="member")])
db.add(room)
db.commit()
# Its name is yours to choose: row 7 is the room chat:7.# Once, for every chat. When someone asks to join chat:7, p["id"] is "7".
def may_join_chat(user, p):
with SessionLocal() as db:
room = db.get(Room, int(p["id"]))
if room is None or room.closed:
return False # no such room, or closed
member = db.query(Member).filter_by(room_id=room.id, user_id=user).first()
if member is None or member.banned:
return False # not a member, or banned
return {"readOnly": True} if member.role == "reader" else True
realtime.room("chat:{id}", may_join_chat, presence=True, emit=["message"])# A room is a row of yours. Nothing is created in the cloud.
room = Room(name="Team", members=[Member(user_id=session["user_id"], role="member")])
db.session.add(room)
db.session.commit()
# Its name is yours to choose: row 7 is the room chat:7.# Once, for every chat. When someone asks to join chat:7, p["id"] is "7".
def may_join_chat(user, p):
room = db.session.get(Room, int(p["id"]))
if room is None or room.closed:
return False # no such room, or closed
member = Member.query.filter_by(room_id=room.id, user_id=user).first()
if member is None or member.banned:
return False # not a member, or banned
return {"readOnly": True} if member.role == "reader" else True
realtime.room("chat:{id}", may_join_chat, presence=True, emit=["message"])-- A room is a row of yours. Nothing is created in the cloud.
INSERT INTO rooms (name) VALUES ('Team');
INSERT INTO members (room_id, user_id, role) VALUES (7, 42, 'member');
-- Its name is yours to choose: row 7 is the room chat:7.// In Go, on the example in the docs. Any language does the same, and sealing is one step more.
// Your /auth route asks this for each room a page wants. For chat:7, id is "7".
func roomRule(room, user string) (*wordplus.Room, string) {
id, isChat := strings.CutPrefix(room, "chat:")
if !isChat {
return nil, "no_rule"
}
row := findRoom(id)
if row == nil || row.Closed {
return nil, "forbidden" // no such room, or closed
}
member := findMember(id, user)
if member == nil || member.Banned {
return nil, "forbidden" // not a member, or banned
}
return &wordplus.Room{
Presence: true,
Emit: []string{"message"},
ReadOnly: member.Role == "reader",
Info: profile(user),
}, ""
}Unirse y enviar
Una página se une por el nombre y tu regla responde. Después oye lo que se envía a la sala y envía a ella, según lo que la regla permita. draw y el resto son tus propias funciones.
Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
import { connect } from '@wordplus/realtime';
const rt = await connect();
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const config = document.getElementById( 'realtime' ).textContent;
const rt = await connect( JSON.parse( config ) );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const config = document.getElementById( 'realtime' ).textContent;
const rt = await connect( JSON.parse( config ) );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );import { connect } from '@wordplus/realtime';
const settings = await fetch( '/api/realtime/config' );
const rt = await connect( await settings.json() );
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:7' );
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
chat.on( 'error', ( e ) => showOut( e.code ) ); // forbidden: your rule said no
chat.on( 'kicked', () => showOut( 'kicked' ) );
chat.emit( 'message', { text: 'Hi' } );'use client'; // in Next.js
import { useRoom } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Chat( { id } ) {
const chat = useRoom( `chat:${ id }`, {
message: ( data, meta ) => draw( data.text, meta.from ),
} );
// forbidden when your rule says no, kicked when they are taken out.
if ( chat.error ) return <p>You are not in this room.</p>;
return <SendBox onSend={ ( text ) => chat.emit( 'message', { text } ) } />;
}<script setup>
import { useRoom } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const { error, emit } = useRoom( 'chat:7', {
message: ( data, meta ) => draw( data.text, meta.from ),
} );
</script>
<template>
<!-- forbidden when your rule says no, kicked when they are taken out -->
<p v-if="error">You are not in this room.</p>
<SendBox v-else @send="( text ) => emit( 'message', { text } )" />
</template><script>
import { useRoom } from '@wordplus/realtime/svelte';
import SendBox from './SendBox.svelte';
// provideRealtime() once, in your root component.
const chat = useRoom( 'chat:7', {
message: ( data, meta ) => draw( data.text, meta.from ),
} );
</script>
<!-- forbidden when your rule says no, kicked when they are taken out -->
{#if chat.error}
<p>You are not in this room.</p>
{:else}
<SendBox onsend={ ( text ) => chat.emit( 'message', { text } ) } />
{/if}import { Component, signal } from '@angular/core';
import type { Room } from '@wordplus/realtime';
// realtime.ts, one connection for the whole app:
// export const realtime = connect();
import { realtime } from './realtime';
import { SendBox } from './send-box';
@Component( {
selector: 'app-chat',
imports: [ SendBox ],
template: `
@if ( out() ) {
<p>You are not in this room.</p>
} @else {
<app-send-box (send)="send( $event )" />
}
`,
} )
export class ChatComponent {
chat?: Room;
out = signal( false );
async ngOnInit() {
this.chat = ( await realtime ).join( 'chat:7' );
this.chat.on( 'message', ( data, meta ) => draw( data.text, meta.from ) );
this.chat.on( 'error', () => this.out.set( true ) ); // forbidden: your rule said no
this.chat.on( 'kicked', () => this.out.set( true ) );
}
send( text: string ) {
this.chat?.emit( 'message', { text } );
}
async ngOnDestroy() {
( await realtime ).leave( 'chat:7' );
}
}let chat = rt.join("chat:7")
chat.on("message") { data, meta in draw(data["text"]?.string ?? "", meta.from) }
chat.on("error") { error, _ in showOut(error["code"]?.string ?? "") } // forbidden: your rule said no
chat.on("kicked") { _, _ in showOut("kicked") }
chat.emit("message", ["text": "Hi"])val chat = rt.join("chat:7")
chat.on("message") { data, meta -> draw(data.jsonObject["text"]?.jsonPrimitive?.content ?: "", meta.from) }
chat.on("error") { error, _ -> showOut(error.jsonObject["code"]?.jsonPrimitive?.content ?: "") } // forbidden: your rule said no
chat.on("kicked") { _, _ -> showOut("kicked") }
chat.emit("message", buildJsonObject { put("text", "Hi") })import { Text } from 'react-native';
import { useRoom } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Chat( { id } ) {
const chat = useRoom( `chat:${ id }`, {
message: ( data, meta ) => draw( data.text, meta.from ),
} );
// forbidden when your rule says no, kicked when they are taken out.
if ( chat.error ) return <Text>You are not in this room.</Text>;
return <SendBox onSend={ ( text ) => chat.emit( 'message', { text } ) } />;
}final chat = rt.join('chat:7');
chat.on('message', (data, meta) => draw(data['text'], meta.from));
chat.on('error', (error, _) => showOut(error['code'])); // forbidden: your rule said no
chat.on('kicked', (_, _) => showOut('kicked'));
chat.emit('message', {'text': 'Hi'});// Your server sends to the room too.
await realtime.to( 'chat:7' ).emit( 'message', { text: 'Welcome' } );// Your server sends to the room too.
await realtime.to( 'chat:7' ).emit( 'message', { text: 'Welcome' } );// Your server sends to the room too.
await realtime.to( 'chat:7' ).emit( 'message', { text: 'Welcome' } );// Your server sends to the room too.
Realtime::to( 'chat:7' )->emit( 'message', [ 'text' => 'Welcome' ] );// Your server sends to the room too.
$realtime->to( 'chat:7' )->emit( 'message', [ 'text' => 'Welcome' ] );# Your server sends to the room too.
realtime.to("chat:7").emit("message", {"text": "Welcome"})# Your server sends to the room too. In an async route, await aemit().
realtime.to("chat:7").emit("message", {"text": "Welcome"})# Your server sends to the room too.
realtime.to("chat:7").emit("message", {"text": "Welcome"})# Your server sends to the room too. wordplus is a signed curl, on the signing page of the docs.
wordplus POST /wordplus/realtime/emit '{"rooms":["chat:7"],"event":"message","data":{"text":"Welcome"}}'Confirmar y guardar un mensaje
Enviar con un ack le dice a la página cuándo la nube ha recibido un mensaje, o por qué tu regla lo rechazó. Después, el webhook entrega cada uno a tu servidor para guardarlo en tu base de datos, ya que la nube guarda los eventos solo para las reconexiones. markSent y db son tuyos.
Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );// Once the cloud has checked it, kept it and sent it on: its id and time.
// Your rule saying no rejects it, with a code.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );
markSent( id, at );const rt = window.Echo.connector.rt; // the connection Echo made
const chat = rt.join( 'chat:7' );
// Once the cloud has checked it, kept it and sent it on: its id and time.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );const chat = useRoom( 'chat:7' );
// Once the cloud has checked it, kept it and sent it on: its id and time.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );<script setup>
import { useRoom } from '@wordplus/realtime/vue';
const { emitWithAck } = useRoom( 'chat:7' );
// Once the cloud has checked it, kept it and sent it on: its id and time.
const send = async ( text ) => markSent( await emitWithAck( 'message', { text } ) );
</script><script>
import { useRoom } from '@wordplus/realtime/svelte';
const chat = useRoom( 'chat:7' );
// Once the cloud has checked it, kept it and sent it on: its id and time.
const send = async ( text ) => markSent( await chat.emitWithAck( 'message', { text } ) );
</script>// Once the cloud has checked it, kept it and sent it on: its id and time.
async send( text: string ) {
const { id, at } = await this.chat!.emitWithAck( 'message', { text } );
markSent( id, at );
}// Once the cloud has checked it, kept it and sent it on: ack.id, ack.at.
let ack = try await chat.emitWithAck("message", ["text": "Hi"])// Once the cloud has checked it, kept it and sent it on: ack.id, ack.at.
val ack = chat.emitWithAck("message", buildJsonObject { put("text", "Hi") })const chat = useRoom( 'chat:7' );
// Once the cloud has checked it, kept it and sent it on: its id and time.
const { id, at } = await chat.emitWithAck( 'message', { text: 'Hi' } );// Once the cloud has checked it, kept it and sent it on: ack.id, ack.at.
final ack = await chat.emitWithAck('message', {'text': 'Hi'});// The webhook gives your server what pages send. Keep it once, by the id the pages saw.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await db.message.upsert( { id: event_id, room, from, text: data.text, at } );
} );// The webhook gives your server what pages send. Keep it once, by the id the pages saw.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await db.message.upsert( { id: event_id, room, from, text: data.text, at } );
} );// The webhook gives your server what pages send. Keep it once, by the id the pages saw.
realtime.on( 'message', async ( { room, from, data, event_id, at } ) => {
await db.message.upsert( { id: event_id, room, from, text: data.text, at } );
} );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// The webhook gives your server what pages send. Keep it once, by the id the pages saw.
$realtime->on( 'message', function ( array $e ) {
Message::updateOrCreate( [ 'id' => $e['event_id'] ], [ 'room' => $e['room'], 'from' => $e['from'], 'text' => $e['data']['text'] ] );
} );
} );// The webhook gives your server what pages send. Keep it once, by the id the pages saw.
$realtime->on( 'message', function ( array $e ) {
save_message( $e['event_id'], $e['room'], $e['from'], $e['data']['text'], $e['at'] );
} );# The webhook gives your server what pages send. Keep it once, by the id the pages saw.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
realtime.on("message", keep_message)# The webhook gives your server what pages send. Keep it once, by the id the pages saw.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
realtime.on("message", keep_message)# The webhook gives your server what pages send. Keep it once, by the id the pages saw.
def keep_message(e):
save_message(e["event_id"], e["room"], e["from"], e["data"]["text"], e["at"])
realtime.on("message", keep_message)// In your webhook route, once its signature is checked as the docs say.
// Keep it once, by the id the pages saw.
if event.Type == "message" {
saveMessage(event.EventID, event.Room, event.From, event.Data["text"], event.At)
}Mostrar quién está escribiendo
Lo que solo importa ahora se envía como volatile: se descarta en lugar de ponerse en cola sin conexión, y nunca se guarda. Llega a todos los demás de la sala, también a las otras pestañas de quien lo envía. showTyping es tu propia función.
// Pages may send what your rule lists.
realtime.room( 'chat:{id}', mayJoin, { presence: true, emit: [ 'message', 'typing' ] } );// Pages may send what your rule lists.
realtime.room( 'chat:{id}', mayJoin, { presence: true, emit: [ 'message', 'typing' ] } );// Pages may send what your rule lists.
realtime.room( 'chat:{id}', mayJoin, { presence: true, emit: [ 'message', 'typing' ] } );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// Pages may send what your rule lists.
$realtime->room( 'chat:{id}', $mayJoin, [ 'presence' => true, 'emit' => [ 'message', 'typing' ] ] );
} );// Pages may send what your rule lists.
$realtime->room( 'chat:{id}', $may_join, [ 'presence' => true, 'emit' => [ 'message', 'typing' ] ] );# Pages may send what your rule lists.
realtime.room("chat:{id}", may_join, presence=True, emit=["message", "typing"])# Pages may send what your rule lists.
realtime.room("chat:{id}", may_join, presence=True, emit=["message", "typing"])# Pages may send what your rule lists.
realtime.room("chat:{id}", may_join, presence=True, emit=["message", "typing"])// In your /auth route, in Go on the example in the docs. Pages may send what the room lists.
room := wordplus.Room{Presence: true, Emit: []string{"message", "typing"}}Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );const chat = window.Echo.connector.rt.join( 'chat:7' );
// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit( 'typing', { on: true } );
chat.on( 'typing', ( data, meta ) => showTyping( meta.from, data.on ) );const chat = useRoom( 'chat:7' );
const typing = useTyping( chat ); // the ids of those typing, gone when they stop
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room?.volatile.emit( 'typing', { on: true } );<script setup>
import { useRoom, useTyping } from '@wordplus/realtime/vue';
const chat = useRoom( 'chat:7' );
const typing = useTyping( chat ); // the ids of those typing, gone when they stop
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room.value?.volatile.emit( 'typing', { on: true } );
</script><script>
import { useRoom, useTyping } from '@wordplus/realtime/svelte';
const chat = useRoom( 'chat:7' );
const typing = useTyping( chat ); // typing.current: the ids of those typing
// Volatile: dropped rather than queued while offline, and never kept.
const onKey = () => chat.room?.volatile.emit( 'typing', { on: true } );
</script>// Volatile: dropped rather than queued while offline, and never kept.
onKey() {
this.chat?.volatile.emit( 'typing', { on: true } );
}// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit("typing", ["on": true])
chat.on("typing") { data, meta in showTyping(meta.from, data["on"]?.bool ?? false) }// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit("typing", buildJsonObject { put("on", true) })
chat.on("typing") { data, meta -> showTyping(meta.from, data.jsonObject["on"]) }const chat = useRoom( 'chat:7' );
const typing = useTyping( chat ); // the ids of those typing, gone when they stop
// Volatile: dropped rather than queued while offline, and never kept.
const onChangeText = () => chat.room?.volatile.emit( 'typing', { on: true } );// Volatile: dropped rather than queued while offline, and never kept.
chat.volatile.emit('typing', {'on': true});
chat.on('typing', (data, meta) => showTyping(meta.from, data['on']));Ponerse al día tras una reconexión
Una sala a la que tu regla da historial guarda sus últimos eventos hasta 5 minutos. Una página que vuelve recibe lo que se perdió, en orden, antes de lo que venga después, también cuando vuelve por otro de nuestros servidores. mayJoin y draw son tuyos.
// Keeps its last 50 events, for 5 minutes at most.
realtime.room( 'chat:{id}', mayJoin, { history: { last: 50, seconds: 300 }, emit: [ 'message' ] } );// Keeps its last 50 events, for 5 minutes at most.
realtime.room( 'chat:{id}', mayJoin, { history: { last: 50, seconds: 300 }, emit: [ 'message' ] } );// Keeps its last 50 events, for 5 minutes at most.
realtime.room( 'chat:{id}', mayJoin, { history: { last: 50, seconds: 300 }, emit: [ 'message' ] } );$this->callAfterResolving( Realtime::class, function ( Realtime $realtime ) {
// Keeps its last 50 events, for 5 minutes at most.
$realtime->room( 'chat:{id}', $mayJoin, [ 'history' => [ 'last' => 50, 'seconds' => 300 ], 'emit' => [ 'message' ] ] );
} );// Keeps its last 50 events, for 5 minutes at most.
$realtime->room( 'chat:{id}', $may_join, [ 'history' => [ 'last' => 50, 'seconds' => 300 ], 'emit' => [ 'message' ] ] );# Keeps its last 50 events, for 5 minutes at most.
realtime.room("chat:{id}", may_join, history={"last": 50, "seconds": 300}, emit=["message"])# Keeps its last 50 events, for 5 minutes at most.
realtime.room("chat:{id}", may_join, history={"last": 50, "seconds": 300}, emit=["message"])# Keeps its last 50 events, for 5 minutes at most.
realtime.room("chat:{id}", may_join, history={"last": 50, "seconds": 300}, emit=["message"])// In your /auth route, in Go on the example in the docs. Its last 50 events, for 5 minutes.
room := wordplus.Room{History: 50, Emit: []string{"message"}}Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
// Or read back through it yourself, the newest first by pages.
const { events, more } = await chat.history( { limit: 50 } );const chat = window.Echo.connector.rt.join( 'chat:7' );
// A page back on the line gets what it missed first, in order, with meta.replayed.
chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );// A page back on the line gets what it missed first, in order, with meta.replayed.
useRoom( 'chat:7', {
message: ( data, meta ) => draw( data.text, meta.from, meta.replayed ),
} );<script setup>
import { useRoom } from '@wordplus/realtime/vue';
// A page back on the line gets what it missed first, in order, with meta.replayed.
useRoom( 'chat:7', {
message: ( data, meta ) => draw( data.text, meta.from, meta.replayed ),
} );
</script><script>
import { useRoom } from '@wordplus/realtime/svelte';
// A page back on the line gets what it missed first, in order, with meta.replayed.
useRoom( 'chat:7', {
message: ( data, meta ) => draw( data.text, meta.from, meta.replayed ),
} );
</script>async ngOnInit() {
this.chat = ( await realtime ).join( 'chat:7' );
// A page back on the line gets what it missed first, in order, with meta.replayed.
this.chat.on( 'message', ( data, meta ) => draw( data.text, meta.from, meta.replayed ) );
}// An app back on the line gets what it missed first, in order, with meta.replayed.
chat.on("message") { data, meta in draw(data["text"]?.string ?? "", meta.from, meta.replayed) }// An app back on the line gets what it missed first, in order, with meta.replayed.
chat.on("message") { data, meta ->
draw(data.jsonObject["text"]?.jsonPrimitive?.content ?: "", meta.from, meta.replayed)
}// An app back on the line gets what it missed first, in order, with meta.replayed.
useRoom( 'chat:7', {
message: ( data, meta ) => draw( data.text, meta.from, meta.replayed ),
} );// An app back on the line gets what it missed first, in order, with meta.replayed.
chat.on('message', (data, meta) => draw(data['text'], meta.from, meta.replayed));Enviar a una persona
Tu servidor envía a un usuario por su id, a cada pestaña y dispositivo que tenga abiertos, sin ninguna sala a la que unirse. Quien no tenga nada abierto no recibe nada, así que guarda lo importante en tu base de datos. showNotice es tu propia función.
// To every tab and device they have open. 'notice' is a name of your own.
await realtime.toUser( 43 ).emit( 'notice', { text: 'Your order shipped' } );
// To several people at once, up to 1,000.
await realtime.toUser( [ 34, 43 ] ).emit( 'notice', { text: 'Starting soon' } );// To every tab and device they have open. 'notice' is a name of your own.
await realtime.toUser( 43 ).emit( 'notice', { text: 'Your order shipped' } );
// To several people at once, up to 1,000.
await realtime.toUser( [ 34, 43 ] ).emit( 'notice', { text: 'Starting soon' } );// To every tab and device they have open. 'notice' is a name of your own.
await realtime.toUser( 43 ).emit( 'notice', { text: 'Your order shipped' } );
// To several people at once, up to 1,000.
await realtime.toUser( [ 34, 43 ] ).emit( 'notice', { text: 'Starting soon' } );// To every tab and device they have open. 'notice' is a name of your own.
Realtime::toUser( 43 )->emit( 'notice', [ 'text' => 'Your order shipped' ] );
// To several people at once, up to 1,000.
Realtime::toUser( [ 34, 43 ] )->emit( 'notice', [ 'text' => 'Starting soon' ] );// To every tab and device they have open. 'notice' is a name of your own.
$realtime->toUser( 43 )->emit( 'notice', [ 'text' => 'Your order shipped' ] );
// To several people at once, up to 1,000.
$realtime->toUser( [ 34, 43 ] )->emit( 'notice', [ 'text' => 'Starting soon' ] );# To every tab and device they have open. "notice" is a name of your own.
realtime.to_user(43).emit("notice", {"text": "Your order shipped"})
# To several people at once, up to 1,000.
realtime.to_user([34, 43]).emit("notice", {"text": "Starting soon"})# In a def route, as these calls block.
# To every tab and device they have open. "notice" is a name of your own.
realtime.to_user(43).emit("notice", {"text": "Your order shipped"})
# To several people at once, up to 1,000.
realtime.to_user([34, 43]).emit("notice", {"text": "Starting soon"})# To every tab and device they have open. "notice" is a name of your own.
realtime.to_user(43).emit("notice", {"text": "Your order shipped"})
# To several people at once, up to 1,000.
realtime.to_user([34, 43]).emit("notice", {"text": "Starting soon"})# To every tab and device they have open. "notice" is a name of your own.
wordplus POST /wordplus/realtime/emit \
'{"users":["43"],"event":"notice","data":{"text":"Your order shipped"}}'
# To several people at once, up to 1,000.
wordplus POST /wordplus/realtime/emit \
'{"users":["34","43"],"event":"notice","data":{"text":"Starting soon"}}'Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// On the connection, with no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );window.Echo.connector.rt.on( 'notice', ( data ) => showNotice( data.text ) );useUserEvent( 'notice', ( data ) => showNotice( data.text ) );<script setup>
import { useUserEvent } from '@wordplus/realtime/vue';
useUserEvent( 'notice', ( data ) => showNotice( data.text ) );
</script><script>
import { useUserEvent } from '@wordplus/realtime/svelte';
useUserEvent( 'notice', ( data ) => showNotice( data.text ) );
</script>async ngOnInit() {
( await realtime ).on( 'notice', ( data ) => showNotice( data.text ) );
}rt.on("notice") { data, _ in showNotice(data["text"]?.string ?? "") }rt.on("notice") { data, _ -> showNotice(data.jsonObject["text"]?.jsonPrimitive?.content ?: "") }useUserEvent( 'notice', ( data ) => showNotice( data.text ) );rt.on('notice', (data, _) => showNotice(data['text']));Enviar a todos
Tu servidor envía a cada página y app conectada ahora, con sesión o sin ella, sin ninguna sala a la que unirse. Cualquiera puede estar conectado, así que lo que lleva no va sellado: úsalo para lo que cualquiera pueda leer. showNotice es tu propia función.
// Every page and app connected now, signed in or not.
await realtime.toEveryone().emit( 'notice', { text: 'New version is out' } );// Every page and app connected now, signed in or not.
await realtime.toEveryone().emit( 'notice', { text: 'New version is out' } );// Every page and app connected now, signed in or not.
await realtime.toEveryone().emit( 'notice', { text: 'New version is out' } );// Every page and app connected now, signed in or not.
Realtime::toEveryone()->emit( 'notice', [ 'text' => 'New version is out' ] );// Every page and app connected now, signed in or not.
$realtime->toEveryone()->emit( 'notice', [ 'text' => 'New version is out' ] );# Every page and app connected now, signed in or not.
realtime.to_everyone().emit("notice", {"text": "New version is out"})# In a def route, as these calls block.
# Every page and app connected now, signed in or not.
realtime.to_everyone().emit("notice", {"text": "New version is out"})# Every page and app connected now, signed in or not.
realtime.to_everyone().emit("notice", {"text": "New version is out"})# Every page and app connected now, signed in or not.
wordplus POST /wordplus/realtime/emit \
'{"everyone":true,"event":"notice","data":{"text":"New version is out"}}'Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
window.Echo.connector.rt.on( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
useUserEvent( 'notice', ( data ) => showNotice( data.text ) );<script setup>
import { useUserEvent } from '@wordplus/realtime/vue';
// With no room to join.
useUserEvent( 'notice', ( data ) => showNotice( data.text ) );
</script><script>
import { useUserEvent } from '@wordplus/realtime/svelte';
// With no room to join.
useUserEvent( 'notice', ( data ) => showNotice( data.text ) );
</script>async ngOnInit() {
// With no room to join.
( await realtime ).on( 'notice', ( data ) => showNotice( data.text ) );
}// With no room to join.
rt.on("notice") { data, _ in showNotice(data["text"]?.string ?? "") }// With no room to join.
rt.on("notice") { data, _ ->
showNotice(data.jsonObject["text"]?.jsonPrimitive?.content ?: "")
}// With no room to join.
useUserEvent( 'notice', ( data ) => showNotice( data.text ) );// With no room to join.
rt.on('notice', (data, _) => showNotice(data['text']));Ver quién está en una sala
Una sala cuya regla dice presence muestra a todos los que están en ella quién está dentro, cada uno con el nombre y la imagen de tu perfil. Quien tiene varias pestañas es un solo miembro. Se muestran los primeros 1000, y el recuento sigue a cualquier tamaño.
Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// The rule of chat:7 says presence: true, so the room lists who is in it.
const chat = rt.join( 'chat:7' );
// Who is in it now, as [ id, info ], and again after each reconnect.
chat.on( 'joined', () => showMembers( [ ...chat.members ] ) );
// Who comes and goes. info is your profile: their name and avatar.
chat.on( 'join', ( { id, info } ) => addMember( id, info.name ) );
chat.on( 'leave', ( { id } ) => removeMember( id ) );
// How many, at any size, at most once a second.
chat.on( 'count', ( n ) => showCount( n ) );// Each member as your profile gives them.
window.Echo.join( 'chat:7' )
.here( ( members ) => showMembers( members ) )
.joining( ( member ) => addMember( member ) )
.leaving( ( member ) => removeMember( member ) );'use client'; // in Next.js
import { usePresence } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Members() {
const members = usePresence( 'chat:7' );
return (
<ul>
{ members.map( ( member ) => <li key={ member.id }>{ member.info.name }</li> ) }
</ul>
);
}<script setup>
import { usePresence } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const members = usePresence( 'chat:7' );
</script>
<template>
<ul>
<li v-for="member in members" :key="member.id">{{ member.info.name }}</li>
</ul>
</template><script>
import { usePresence } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const members = usePresence( 'chat:7' );
</script>
<ul>
{#each members.current as member (member.id)}
<li>{ member.info.name }</li>
{/each}
</ul>import { Component, signal } from '@angular/core';
import { realtime } from './realtime';
@Component( {
selector: 'app-members',
template: `
<ul>
@for ( member of members(); track member[ 0 ] ) {
<li>{{ member[ 1 ].name }}</li>
}
</ul>
`,
} )
export class MembersComponent {
members = signal<[ string, any ][]>( [] );
async ngOnInit() {
const chat = ( await realtime ).join( 'chat:7' );
const update = () => this.members.set( [ ...chat.members ] );
chat.on( 'joined', update );
chat.on( 'join', update );
chat.on( 'leave', update );
}
}let chat = rt.join("chat:7")
for event in ["joined", "join", "leave"] {
chat.on(event) { _, _ in
showMembers(chat.members.map { id, info in info["name"]?.string ?? id })
}
}val chat = rt.join("chat:7")
for (event in listOf("joined", "join", "leave")) {
chat.on(event) { _, _ ->
showMembers(chat.members.map { (id, info) ->
info.jsonObject["name"]?.jsonPrimitive?.content ?: id
})
}
}import { Text } from 'react-native';
import { usePresence } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Members() {
const members = usePresence( 'chat:7' );
return members.map( ( member ) => <Text key={ member.id }>{ member.info.name }</Text> );
}final chat = rt.join('chat:7');
for (final event in ['joined', 'join', 'leave']) {
chat.on(event, (_, _) {
showMembers([
for (final MapEntry(key: id, value: info) in chat.members.entries)
info?['name'] ?? id,
]);
});
}// Ask from your server: [ { id, info } ], with their info opened for you.
const { count, list } = await realtime.room( 'chat:7' ).members();// Ask from your server: [ { id, info } ], with their info opened for you.
const { count, list } = await realtime.room( 'chat:7' ).members();// Ask from your server: [ { id, info } ], with their info opened for you.
const { count, list } = await realtime.room( 'chat:7' ).members();// Ask from your server: [ [ 'id', 'info' ] ], with their info opened for you.
$members = Realtime::room( 'chat:7' )->members();
$members['count'];
$members['list'];// Ask from your server: [ [ 'id', 'info' ] ], with their info opened for you.
$members = $realtime->room( 'chat:7' )->members();
$members['count'];
$members['list'];# Ask from your server: [{"id", "info"}], with their info opened for you.
members = realtime.room("chat:7").members()
members["count"]
members["list"]# In a def route, as these calls block.
# Ask from your server: [{"id", "info"}], with their info opened for you.
members = realtime.room("chat:7").members()
members["count"]
members["list"]# Ask from your server: [{"id", "info"}], with their info opened for you.
members = realtime.room("chat:7").members()
members["count"]
members["list"]# Ask from your server: count, and each member's id and info.
wordplus GET '/wordplus/realtime/rooms/chat%3A7?members=1'Ver quién está en línea
Alguien a quien tu servidor identificó está en línea mientras alguna de sus páginas o apps esté conectada, y desconectado 10 segundos después de cerrarse la última. Cualquiera con sesión puede observar hasta 1000 personas. Una función hidden en tu configuración deja fuera a quienes eligieron ocultar su estado.
Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );// Their status now, then each change, for up to 1,000 people.
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
// How many are online across your app, live.
rt.online.on( 'count', ( n ) => showCount( n ) );
// Everyone online, a page at a time.
const { ids, next } = await rt.online.list();
showOnline( ids );const rt = window.Echo.connector.rt; // the connection Echo made
rt.online.watch( [ 34, 43 ] ).on( 'change', ( { id, online } ) => showDot( id, online ) );
rt.online.on( 'count', ( n ) => showCount( n ) );'use client'; // in Next.js
import { useOnline } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Team() {
const { online, count } = useOnline( [ 34, 43 ], { count: true } );
return (
<>
<p>Ann is { online[ 34 ] ? 'online' : 'away' }</p>
<p>{ count } online now</p>
</>
);
}<script setup>
import { useOnline } from '@wordplus/realtime/vue';
// provideRealtime() once, in your root component.
const { online, count } = useOnline( [ 34, 43 ], { count: true } );
</script>
<template>
<p>Ann is {{ online[ 34 ] ? 'online' : 'away' }}</p>
<p>{{ count }} online now</p>
</template><script>
import { useOnline } from '@wordplus/realtime/svelte';
// provideRealtime() once, in your root component.
const team = useOnline( [ 34, 43 ], { count: true } );
</script>
<p>Ann is { team.online[ 34 ] ? 'online' : 'away' }</p>
<p>{ team.count } online now</p>import { Component, signal } from '@angular/core';
import { realtime } from './realtime';
@Component( {
selector: 'app-team',
template: `
<p>Ann is {{ annOnline() ? 'online' : 'away' }}</p>
<p>{{ count() }} online now</p>
`,
} )
export class TeamComponent {
annOnline = signal( false );
count = signal( 0 );
async ngOnInit() {
const rt = await realtime;
rt.online.watch( [ 34, 43 ] ).on( 'change', ( change ) => {
if ( change.id === '34' ) this.annOnline.set( change.online );
} );
rt.online.on( 'count', ( n ) => this.count.set( n ) );
}
}let people = ["34", "43"]
rt.online.watch(people).on("change") { _ in
showOnline(people.filter { rt.online.has($0) })
}
rt.online.on("count") { data in showCount(data["n"]?.number ?? 0) }
// Once connected: everyone online, a page at a time.
let (ids, next) = try await rt.online.list()val people = listOf("34", "43")
rt.online.watch(people).on("change") {
showOnline(people.filter { rt.online.has(it) })
}
rt.online.on("count") { data ->
showCount(data.jsonObject["n"]?.jsonPrimitive?.int ?: 0)
}
// Once connected: everyone online, a page at a time.
val (ids, next) = rt.online.list()import { Text } from 'react-native';
import { useOnline } from '@wordplus/realtime/react';
// Inside <RealtimeProvider>, once for the whole app.
export function Team() {
const { online, count } = useOnline( [ 34, 43 ], { count: true } );
return (
<>
<Text>Ann is { online[ 34 ] ? 'online' : 'away' }</Text>
<Text>{ count } online now</Text>
</>
);
}final people = ['34', '43'];
rt.online.watch(people).on('change', (_) {
showOnline(people.where(rt.online.has).toList());
});
rt.online.on('count', (data) => showCount(data['n']));
// Once connected: everyone online, a page at a time.
final page = await rt.online.list();// Ask from your server.
const isOnline = await realtime.online.has( 43 );
const states = await realtime.online.states( [ 34, 43 ] ); // [ { id, online, at? } ]
const count = await realtime.online.count();
const { ids, next } = await realtime.online.list();// Ask from your server.
const isOnline = await realtime.online.has( 43 );
const states = await realtime.online.states( [ 34, 43 ] ); // [ { id, online, at? } ]
const count = await realtime.online.count();
const { ids, next } = await realtime.online.list();// Ask from your server.
const isOnline = await realtime.online.has( 43 );
const states = await realtime.online.states( [ 34, 43 ] ); // [ { id, online, at? } ]
const count = await realtime.online.count();
const { ids, next } = await realtime.online.list();// Ask from your server.
$is_online = Realtime::online()->has( 43 );
$states = Realtime::online()->states( [ 34, 43 ] ); // [ [ 'id', 'online', 'at'? ] ]
$count = Realtime::online()->count();
$page = Realtime::online()->list(); // [ 'ids', 'next' ]// Ask from your server.
$is_online = $realtime->online()->has( 43 );
$states = $realtime->online()->states( [ 34, 43 ] ); // [ [ 'id', 'online', 'at'? ] ]
$count = $realtime->online()->count();
$page = $realtime->online()->list(); // [ 'ids', 'next' ]# Ask from your server.
is_online = realtime.online.has(43)
states = realtime.online.states([34, 43]) # [{"id", "online", "at"?}]
count = realtime.online.count()
page = realtime.online.list() # {"ids", "next"}# In a def route, as these calls block.
# Ask from your server.
is_online = realtime.online.has(43)
states = realtime.online.states([34, 43]) # [{"id", "online", "at"?}]
count = realtime.online.count()
page = realtime.online.list() # {"ids", "next"}# Ask from your server.
is_online = realtime.online.has(43)
states = realtime.online.states([34, 43]) # [{"id", "online", "at"?}]
count = realtime.online.count()
page = realtime.online.list() # {"ids", "next"}# Whether each is online, and how many are across your app.
wordplus GET '/wordplus/realtime/online?ids=34,43'
# Everyone online, a page at a time.
wordplus GET '/wordplus/realtime/online'Añadir a una persona
Añádela a tu tabla y tu regla la dejará entrar desde ese momento. Para meter una página que ya tiene abierta, envíale un evento propio.
await db.member.create( { data: { roomId: 7, userId: 43, role: 'member' } } );
// Tell their open pages. 'added' is a name of your own.
await realtime.toUser( 43 ).emit( 'added', { room: 'chat:7' } );await db.member.create( { data: { roomId: 7, userId: 43, role: 'member' } } );
// Tell their open pages. 'added' is a name of your own.
await realtime.toUser( 43 ).emit( 'added', { room: 'chat:7' } );await db.member.create( { data: { roomId: 7, userId: 43, role: 'member' } } );
// Tell their open pages. 'added' is a name of your own.
await realtime.toUser( 43 ).emit( 'added', { room: 'chat:7' } );RoomMember::create( [ 'room_id' => 7, 'user_id' => 43, 'role' => 'member' ] );
// Tell their open pages. 'added' is a name of your own.
Realtime::toUser( 43 )->emit( 'added', [ 'room' => 'chat:7' ] );$db->prepare( 'INSERT INTO members (room_id, user_id, role) VALUES (?, ?, ?)' )
->execute( [ 7, 43, 'member' ] );
// Tell their open pages. 'added' is a name of your own.
$realtime->toUser( 43 )->emit( 'added', [ 'room' => 'chat:7' ] );Member.objects.create(room_id=7, user_id=43, role="member")
# Tell their open pages. "added" is a name of your own.
realtime.to_user(43).emit("added", {"room": "chat:7"})# In a def route, as these calls block.
db.add(Member(room_id=7, user_id=43, role="member"))
db.commit()
# Tell their open pages. "added" is a name of your own.
realtime.to_user(43).emit("added", {"room": "chat:7"})db.session.add(Member(room_id=7, user_id=43, role="member"))
db.session.commit()
# Tell their open pages. "added" is a name of your own.
realtime.to_user(43).emit("added", {"room": "chat:7"})# In your database: INSERT INTO members (room_id, user_id, role) VALUES (7, 43, 'member')
# Tell their open pages. "added" is a name of your own.
wordplus POST /wordplus/realtime/emit '{"users":["43"],"event":"added","data":{"room":"chat:7"}}'Hooks y componentes para cualquier app de React, con cualquiera de los servidores de arriba.
rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );rt.on( 'added', ( data ) => openChat( data.room ) );window.Echo.connector.rt.on( 'added', ( data ) => openChat( data.room ) );useUserEvent( 'added', ( data ) => openChat( data.room ) );<script setup>
import { useUserEvent } from '@wordplus/realtime/vue';
useUserEvent( 'added', ( data ) => openChat( data.room ) );
</script><script>
import { useUserEvent } from '@wordplus/realtime/svelte';
useUserEvent( 'added', ( data ) => openChat( data.room ) );
</script>async ngOnInit() {
( await realtime ).on( 'added', ( data ) => openChat( data.room ) );
}rt.on("added") { data, _ in openChat(data["room"]?.string ?? "") }rt.on("added") { data, _ -> openChat(data.jsonObject["room"]?.jsonPrimitive?.content ?: "") }useUserEvent( 'added', ( data ) => openChat( data.room ) );rt.on('added', (data, _) => openChat(data['room']));Convertir a alguien en lector
Un lector se une y lo oye todo, y lo que envíe se rechaza. Si ya está dentro, cambia su rol y luego haz que se vuelva a consultar la regla: sus páginas vuelven por sí solas con la nueva respuesta, solo en esta sala.
// A new reader.
await db.member.create( { data: { roomId: 7, userId: 44, role: 'reader' } } );
// Someone already in: change the role, then their pages ask your rule again.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { role: 'reader' } } );
await realtime.room( 'chat:7' ).recheck( 43 );// A new reader.
await db.member.create( { data: { roomId: 7, userId: 44, role: 'reader' } } );
// Someone already in: change the role, then their pages ask your rule again.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { role: 'reader' } } );
await realtime.room( 'chat:7' ).recheck( 43 );// A new reader.
await db.member.create( { data: { roomId: 7, userId: 44, role: 'reader' } } );
// Someone already in: change the role, then their pages ask your rule again.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { role: 'reader' } } );
await realtime.room( 'chat:7' ).recheck( 43 );// A new reader.
RoomMember::create( [ 'room_id' => 7, 'user_id' => 44, 'role' => 'reader' ] );
// Someone already in: change the role, then their pages ask your rule again.
RoomMember::where( [ 'room_id' => 7, 'user_id' => 43 ] )->update( [ 'role' => 'reader' ] );
Realtime::room( 'chat:7' )->recheck( 43 );// A new reader.
$db->prepare( 'INSERT INTO members (room_id, user_id, role) VALUES (?, ?, ?)' )
->execute( [ 7, 44, 'reader' ] );
// Someone already in: change the role, then their pages ask your rule again.
$db->prepare( 'UPDATE members SET role = ? WHERE room_id = ? AND user_id = ?' )
->execute( [ 'reader', 7, 43 ] );
$realtime->room( 'chat:7' )->recheck( 43 );# A new reader.
Member.objects.create(room_id=7, user_id=44, role="reader")
# Someone already in: change the role, then their pages ask your rule again.
Member.objects.filter(room_id=7, user_id=43).update(role="reader")
realtime.room("chat:7").recheck(43)# In a def route, as these calls block.
# A new reader.
db.add(Member(room_id=7, user_id=44, role="reader"))
db.commit()
# Someone already in: change the role, then their pages ask your rule again.
db.query(Member).filter_by(room_id=7, user_id=43).update({"role": "reader"})
db.commit()
realtime.room("chat:7").recheck(43)# A new reader.
db.session.add(Member(room_id=7, user_id=44, role="reader"))
db.session.commit()
# Someone already in: change the role, then their pages ask your rule again.
Member.query.filter_by(room_id=7, user_id=43).update({"role": "reader"})
db.session.commit()
realtime.room("chat:7").recheck(43)# A new reader.
# In your database: INSERT INTO members (room_id, user_id, role) VALUES (7, 44, 'reader')
# Someone already in: change the role, then their pages ask your rule again.
# In your database: UPDATE members SET role = 'reader' WHERE room_id = 7 AND user_id = 43
wordplus POST /wordplus/realtime/rooms/chat%3A7/recheck '{"user":"43"}'Sacar a alguien
Sacar a alguien lo deja fuera al instante, y su página oye kicked. Un miembro puede volver a unirse enseguida, así que para mantenerlo fuera, quítalo antes de tu tabla.
// Out now. They are still a member, so they may come back.
await realtime.room( 'chat:7' ).remove( 43 );
// Out for good: remove them first, and your rule says no from then on.
await db.member.deleteMany( { where: { roomId: 7, userId: 43 } } );
await realtime.room( 'chat:7' ).remove( 43 );// Out now. They are still a member, so they may come back.
await realtime.room( 'chat:7' ).remove( 43 );
// Out for good: remove them first, and your rule says no from then on.
await db.member.deleteMany( { where: { roomId: 7, userId: 43 } } );
await realtime.room( 'chat:7' ).remove( 43 );// Out now. They are still a member, so they may come back.
await realtime.room( 'chat:7' ).remove( 43 );
// Out for good: remove them first, and your rule says no from then on.
await db.member.deleteMany( { where: { roomId: 7, userId: 43 } } );
await realtime.room( 'chat:7' ).remove( 43 );// Out now. They are still a member, so they may come back.
Realtime::room( 'chat:7' )->remove( 43 );
// Out for good: remove them first, and your rule says no from then on.
RoomMember::where( [ 'room_id' => 7, 'user_id' => 43 ] )->delete();
Realtime::room( 'chat:7' )->remove( 43 );// Out now. They are still a member, so they may come back.
$realtime->room( 'chat:7' )->remove( 43 );
// Out for good: remove them first, and your rule says no from then on.
$db->prepare( 'DELETE FROM members WHERE room_id = ? AND user_id = ?' )->execute( [ 7, 43 ] );
$realtime->room( 'chat:7' )->remove( 43 );# Out now. They are still a member, so they may come back.
realtime.room("chat:7").remove(43)
# Out for good: remove them first, and your rule says no from then on.
Member.objects.filter(room_id=7, user_id=43).delete()
realtime.room("chat:7").remove(43)# In a def route, as these calls block.
# Out now. They are still a member, so they may come back.
realtime.room("chat:7").remove(43)
# Out for good: remove them first, and your rule says no from then on.
db.query(Member).filter_by(room_id=7, user_id=43).delete()
db.commit()
realtime.room("chat:7").remove(43)# Out now. They are still a member, so they may come back.
realtime.room("chat:7").remove(43)
# Out for good: remove them first, and your rule says no from then on.
Member.query.filter_by(room_id=7, user_id=43).delete()
db.session.commit()
realtime.room("chat:7").remove(43)# Out now. They are still a member, so they may come back.
wordplus POST /wordplus/realtime/rooms/chat%3A7/kick '{"user":"43"}'
# Out for good: remove them first, and your rule says no from then on.
# In your database: DELETE FROM members WHERE room_id = 7 AND user_id = 43
wordplus POST /wordplus/realtime/rooms/chat%3A7/kick '{"user":"43"}'Vetar a alguien
Un veto es una marca en tu tabla que lee tu regla, junto con sacarlo para dejarlo fuera al instante. Quita la marca y podrá unirse de nuevo.
// The mark your rule reads, then out now.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { banned: true } } );
await realtime.room( 'chat:7' ).remove( 43 );
// Lift it: they can join again.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { banned: false } } );// The mark your rule reads, then out now.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { banned: true } } );
await realtime.room( 'chat:7' ).remove( 43 );
// Lift it: they can join again.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { banned: false } } );// The mark your rule reads, then out now.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { banned: true } } );
await realtime.room( 'chat:7' ).remove( 43 );
// Lift it: they can join again.
await db.member.updateMany( { where: { roomId: 7, userId: 43 }, data: { banned: false } } );// The mark your rule reads, then out now.
RoomMember::where( [ 'room_id' => 7, 'user_id' => 43 ] )->update( [ 'banned' => true ] );
Realtime::room( 'chat:7' )->remove( 43 );
// Lift it: they can join again.
RoomMember::where( [ 'room_id' => 7, 'user_id' => 43 ] )->update( [ 'banned' => false ] );// The mark your rule reads, then out now.
$db->prepare( 'UPDATE members SET banned = 1 WHERE room_id = ? AND user_id = ?' )->execute( [ 7, 43 ] );
$realtime->room( 'chat:7' )->remove( 43 );
// Lift it: they can join again.
$db->prepare( 'UPDATE members SET banned = 0 WHERE room_id = ? AND user_id = ?' )->execute( [ 7, 43 ] );# The mark your rule reads, then out now.
Member.objects.filter(room_id=7, user_id=43).update(banned=True)
realtime.room("chat:7").remove(43)
# Lift it: they can join again.
Member.objects.filter(room_id=7, user_id=43).update(banned=False)# In a def route, as these calls block.
# The mark your rule reads, then out now.
db.query(Member).filter_by(room_id=7, user_id=43).update({"banned": True})
db.commit()
realtime.room("chat:7").remove(43)
# Lift it: they can join again.
db.query(Member).filter_by(room_id=7, user_id=43).update({"banned": False})
db.commit()# The mark your rule reads, then out now.
Member.query.filter_by(room_id=7, user_id=43).update({"banned": True})
db.session.commit()
realtime.room("chat:7").remove(43)
# Lift it: they can join again.
Member.query.filter_by(room_id=7, user_id=43).update({"banned": False})
db.session.commit()# The mark your rule reads, then out now.
# In your database: UPDATE members SET banned = 1 WHERE room_id = 7 AND user_id = 43
wordplus POST /wordplus/realtime/rooms/chat%3A7/kick '{"user":"43"}'
# Lift it: they can join again.
# In your database: UPDATE members SET banned = 0 WHERE room_id = 7 AND user_id = 43Cerrar y reabrir
Cierra la sala en tu tabla, para que tu regla diga que no a todos, y saca de una vez a todos los que estén dentro. Quita la marca para reabrirla.
// Close: your rule now says no to everyone, and whoever is in it goes out.
await db.room.update( { where: { id: 7 }, data: { closed: true } } );
await realtime.room( 'chat:7' ).removeEveryone();
// Reopen: your rule says yes again, and people can join.
await db.room.update( { where: { id: 7 }, data: { closed: false } } );// Close: your rule now says no to everyone, and whoever is in it goes out.
await db.room.update( { where: { id: 7 }, data: { closed: true } } );
await realtime.room( 'chat:7' ).removeEveryone();
// Reopen: your rule says yes again, and people can join.
await db.room.update( { where: { id: 7 }, data: { closed: false } } );// Close: your rule now says no to everyone, and whoever is in it goes out.
await db.room.update( { where: { id: 7 }, data: { closed: true } } );
await realtime.room( 'chat:7' ).removeEveryone();
// Reopen: your rule says yes again, and people can join.
await db.room.update( { where: { id: 7 }, data: { closed: false } } );// Close: your rule now says no to everyone, and whoever is in it goes out.
Room::whereKey( 7 )->update( [ 'closed' => true ] );
Realtime::room( 'chat:7' )->removeEveryone();
// Reopen: your rule says yes again, and people can join.
Room::whereKey( 7 )->update( [ 'closed' => false ] );// Close: your rule now says no to everyone, and whoever is in it goes out.
$db->prepare( 'UPDATE rooms SET closed = 1 WHERE id = ?' )->execute( [ 7 ] );
$realtime->room( 'chat:7' )->removeEveryone();
// Reopen: your rule says yes again, and people can join.
$db->prepare( 'UPDATE rooms SET closed = 0 WHERE id = ?' )->execute( [ 7 ] );# Close: your rule now says no to everyone, and whoever is in it goes out.
Room.objects.filter(pk=7).update(closed=True)
realtime.room("chat:7").remove_everyone()
# Reopen: your rule says yes again, and people can join.
Room.objects.filter(pk=7).update(closed=False)# In a def route, as these calls block.
# Close: your rule now says no to everyone, and whoever is in it goes out.
db.query(Room).filter_by(id=7).update({"closed": True})
db.commit()
realtime.room("chat:7").remove_everyone()
# Reopen: your rule says yes again, and people can join.
db.query(Room).filter_by(id=7).update({"closed": False})
db.commit()# Close: your rule now says no to everyone, and whoever is in it goes out.
Room.query.filter_by(id=7).update({"closed": True})
db.session.commit()
realtime.room("chat:7").remove_everyone()
# Reopen: your rule says yes again, and people can join.
Room.query.filter_by(id=7).update({"closed": False})
db.session.commit()# Close: your rule now says no to everyone, and whoever is in it goes out.
# In your database: UPDATE rooms SET closed = 1 WHERE id = 7
wordplus POST /wordplus/realtime/rooms/chat%3A7/kick '{"everyone":true}'
# Reopen: your rule says yes again, and people can join.
# In your database: UPDATE rooms SET closed = 0 WHERE id = 7Eliminar una sala
Elimina tus filas, saca a todos los que estén dentro y borra lo que la nube guardó para las reconexiones. De la sala no queda nada.
// Your rows first, so your rule says no from here on.
await db.member.deleteMany( { where: { roomId: 7 } } );
await db.room.delete( { where: { id: 7 } } );
// Then whoever is in it goes out, and what was kept for reconnects goes too.
await realtime.room( 'chat:7' ).removeEveryone();
await realtime.room( 'chat:7' ).forget();// Your rows first, so your rule says no from here on.
await db.member.deleteMany( { where: { roomId: 7 } } );
await db.room.delete( { where: { id: 7 } } );
// Then whoever is in it goes out, and what was kept for reconnects goes too.
await realtime.room( 'chat:7' ).removeEveryone();
await realtime.room( 'chat:7' ).forget();// Your rows first, so your rule says no from here on.
await db.member.deleteMany( { where: { roomId: 7 } } );
await db.room.delete( { where: { id: 7 } } );
// Then whoever is in it goes out, and what was kept for reconnects goes too.
await realtime.room( 'chat:7' ).removeEveryone();
await realtime.room( 'chat:7' ).forget();// Your rows first, so your rule says no from here on.
RoomMember::where( 'room_id', 7 )->delete();
Room::destroy( 7 );
// Then whoever is in it goes out, and what was kept for reconnects goes too.
Realtime::room( 'chat:7' )->removeEveryone();
Realtime::room( 'chat:7' )->forget();// Your rows first, so your rule says no from here on.
$db->prepare( 'DELETE FROM members WHERE room_id = ?' )->execute( [ 7 ] );
$db->prepare( 'DELETE FROM rooms WHERE id = ?' )->execute( [ 7 ] );
// Then whoever is in it goes out, and what was kept for reconnects goes too.
$realtime->room( 'chat:7' )->removeEveryone();
$realtime->room( 'chat:7' )->forget();# Your rows first, so your rule says no from here on.
Member.objects.filter(room_id=7).delete()
Room.objects.filter(pk=7).delete()
# Then whoever is in it goes out, and what was kept for reconnects goes too.
realtime.room("chat:7").remove_everyone()
realtime.room("chat:7").forget()# In a def route, as these calls block.
# Your rows first, so your rule says no from here on.
db.query(Member).filter_by(room_id=7).delete()
db.query(Room).filter_by(id=7).delete()
db.commit()
# Then whoever is in it goes out, and what was kept for reconnects goes too.
realtime.room("chat:7").remove_everyone()
realtime.room("chat:7").forget()# Your rows first, so your rule says no from here on.
Member.query.filter_by(room_id=7).delete()
Room.query.filter_by(id=7).delete()
db.session.commit()
# Then whoever is in it goes out, and what was kept for reconnects goes too.
realtime.room("chat:7").remove_everyone()
realtime.room("chat:7").forget()# Your rows first, so your rule says no from here on.
# In your database: DELETE FROM members WHERE room_id = 7
# In your database: DELETE FROM rooms WHERE id = 7
# Then whoever is in it goes out, and what was kept for reconnects goes too.
wordplus POST /wordplus/realtime/rooms/chat%3A7/kick '{"everyone":true}'
wordplus DELETE /wordplus/realtime/rooms/chat%3A7/historyEl chat de equipo de aquí es el comienzo de uno: la API de chat añade el chat listo para usar, el historial, las marcas de lectura, los archivos y la moderación.
Salas en cada stack, con toda la configuración:
WebSockets en Next.js
WebSockets en Express
WebSockets en Laravel
WebSockets en PHP
WebSockets en Django
WebSockets en FastAPI
WebSockets en Flask
WebSockets en iOS
WebSockets en Android
Por qué los WebSockets se complican en tu propio framework: Next.js, Laravel, Django y Flask, FastAPI.
¿Tienes un servidor WebSocket propio? Nuestra prueba de WebSocket lo comprueba desde tu navegador.
En cada conexión
Más que un socket
Un socket transporta bytes. Todo lo que una app construye a su alrededor, desde las reconexiones hasta quién está en línea, ya está hecho.

Nada se pierde al reconectar
Una sala puede guardar sus últimos eventos, y una página que vuelve recibe lo que se perdió, en orden, antes de lo que venga después.
Quién está en línea
Una sala puede mostrar quién está en ella, con lo que elijas mostrar de cada persona. Un contador dice cuántos están viendo una página, a cualquier escala, y quién está en línea se sabe en toda tu app.
Eventos desde la página
Las páginas envían a las salas en las que están, sin ninguna petición a tu servidor: mensajes de chat, escritura, un cursor. La regla dice qué eventos se pueden enviar y un webhook entrega a tu servidor los que debe guardar.
A una persona, en todas partes
Envía a un usuario y le llega en cada pestaña y dispositivo que tenga abierto, sin crear ninguna sala.
Cifrado, con claves que nunca tenemos
Los eventos, la presencia y el historial viajan sellados con claves que guarda tu servidor, y las llamadas entre dos personas están cifradas de extremo a extremo. La nube los transporta sin poder leerlos.
Una conexión para todas las pestañas
Las pestañas de un navegador comparten una sola conexión, así que una persona con tres pestañas abiertas cuenta una vez.
Casos de uso
Lo que se construye con WebSockets
Cada uno es una app completa en la documentación, con su servidor en Node.js, PHP y Python.
Actualizaciones en vivo y notificaciones
Un pedido que avanza en su página, un panel, el progreso de una tarea y un aviso a un usuario en todas sus pestañas y apps.
Chat
Conversaciones entre dos personas y en grupo, con indicador de escritura, confirmaciones de lectura y reacciones, guardadas en tu propia base de datos.
Quién está en línea y quién está aquí
Un punto en cada avatar, las personas de una sala con sus roles y cuántas miran una página.
Edición conjunta
Quién está en un documento, sus cursores y los cambios, enviados en binario y guardados para una reconexión.
Encuestas, cuestionarios y preguntas
Votos y preguntas que llegan solo a tu servidor, resultados enviados a todos y una puntuación para cada jugador.
Subastas en vivo
Pujas que tu servidor decide una a una, el nuevo precio para todos y un reloj que se alarga con una puja de última hora.
Precios
Precio por conexiones, nunca por mensajes
Desde $11.99 al mes por 1000 conexiones simultáneas, con facturación anual, o $14.99 con facturación mensual.
El precio depende de las conexiones simultáneas, a partir de 1000, con facturación mensual o anual. Los mensajes y el ancho de banda nunca se cobran, y lo que envía tu servidor no usa ninguna de tus conexiones.
El mismo plan y el mismo SDK incluyen videollamadas y retransmisión en vivo, sobre la misma conexión.
Dudas
Preguntas frecuentes
¿Necesito mi propio servidor WebSocket?
No. Los navegadores y las apps mantienen sus conexiones abiertas con nuestros servidores, y se inician más a medida que tu app crece. Tu servidor solo dice quién puede unirse a qué y envía cada evento en una petición HTTP corta.
¿Funciona en un alojamiento serverless?
Sí. Una función serverless no puede mantener una conexión abierta y aquí no hace falta: envía cada evento en una petición corta y las conexiones se quedan con nosotros. Las funciones edge y cualquier otro host funcionan igual.
¿Qué stacks pueden usar la API WebSocket?
Next.js y Express, Laravel y PHP puro, Django, FastAPI y Flask, Capacitor, iOS y Android, cada uno con su guía. Las apps de React Native y Flutter también tienen salas y presencia. Un servidor en cualquier otro lenguaje usa la API HTTP.
¿Tengo que escribir yo el código WebSocket?
No. El SDK abre la conexión, se reconecta por sí solo y vuelve a unirse a tus salas, y tú escuchas los eventos por su nombre. En Laravel es un driver de broadcasting, así que broadcast() y tu archivo de canales siguen igual.
¿Qué cuenta como conexión?
Un navegador o un dispositivo conectado a la nube en ese momento. Las pestañas de un navegador comparten una conexión cuando tu app sirve el worker del SDK, y lo que tu servidor envía por la API no cuenta.
¿Qué pasa al llegar a mi límite de conexiones?
Hasta un 20 % más siguen conectándose, y el titular de la cuenta recibe un correo al llegar al 80 % y al 100 %, a tiempo para pasar a un plan mayor.
¿Qué pasa cuando una página pierde la conexión?
Se reconecta por sí sola. Una sala que guarda historial le entrega lo que se perdió, en orden, hasta 5 minutos, y a una página que falta más tiempo se le avisa, para que pueda volver a leer de tu servidor. El historial es solo para reconexiones: tu propia base de datos guarda tus registros.
¿Quién decide quién entra en una sala?
Tu servidor, con una regla para cada tipo de sala: quién entra, qué puede enviar y quién solo lee. La nube hace cumplir cada respuesta, y tu servidor puede sacar a alguien de una sala en cualquier momento.
¿Podéis leer lo que envía mi app?
No en una sala privada o de presencia. Sus eventos, su historial y quién está en ella viajan sellados con claves que crea tu servidor, y la nube los transporta sin poder leerlos. Una sala pública, a la que puede unirse cualquiera, va sin cifrar.
¿Dónde están vuestros servidores?
Los servidores de tiempo real que transportan tus eventos están en Alemania. Los relés y servidores de medios para las llamadas están en más países.
¿Preguntas sobre tu integración? Escríbenos: te ayudamos con los SDK, la pantalla de llamada y tu stack.