A WebSocket signaling server for y-webrtc collaborative editing. This server handles the WebRTC signaling process that enables peer-to-peer connections between clients using Yjs documents.
import * as Y from 'yjs'
import { WebrtcProvider } from 'y-webrtc'
// Create a Yjs document
const ydoc = new Y.Doc()
// Connect to the signaling server
const provider = new WebrtcProvider('my-room-name', ydoc, {
signaling: ['ws://your-val-town-url.web.val.run']
})
// Use shared types
const ytext = ydoc.getText('shared-text')
const ymap = ydoc.getMap('shared-map')
import { useEffect, useState } from 'react'
import * as Y from 'yjs'
import { WebrtcProvider } from 'y-webrtc'
function CollaborativeEditor({ roomName }) {
const [ydoc] = useState(() => new Y.Doc())
const [provider, setProvider] = useState(null)
const [text, setText] = useState('')
useEffect(() => {
// Connect to signaling server
const webrtcProvider = new WebrtcProvider(roomName, ydoc, {
signaling: ['ws://your-val-town-url.web.val.run']
})
const ytext = ydoc.getText('content')
// Listen for changes
const updateText = () => setText(ytext.toString())
ytext.observe(updateText)
updateText()
setProvider(webrtcProvider)
return () => {
webrtcProvider.destroy()
}
}, [roomName, ydoc])
const handleChange = (newText) => {
const ytext = ydoc.getText('content')
ydoc.transact(() => {
ytext.delete(0, ytext.length)
ytext.insert(0, newText)
})
}
return (
<textarea
value={text}
onChange={(e) => handleChange(e.target.value)}
placeholder="Start typing to collaborate..."
/>
)
}
ws://your-val-town-url.web.val.runReturns a web interface with server information and real-time statistics.
Returns JSON with current server statistics:
{ "totalRooms": 3, "totalClients": 7, "rooms": [ { "id": "room-1", "clients": 3, "lastActivity": "2024-01-15T10:30:00.000Z" } ] }
Health check endpoint:
{ "status": "ok", "timestamp": "2024-01-15T10:30:00.000Z" }
The server expects JSON messages with the following structure:
{ "type": "join", "room": "room-name", "peerId": "unique-peer-id" }
{ "type": "leave" }
{ "type": "signal", "data": { // WebRTC signaling data (offer, answer, ice candidates, etc.) } }
The server sends messages in the same format:
{ "type": "signal", "peerId": "peer-id", "data": { "type": "peer-joined" } }{ "type": "signal", "peerId": "peer-id", "data": { "type": "peer-left" } }{ "type": "signal", "data": { "type": "room-joined", "peers": ["peer1", "peer2"] } }{ "type": "signal", "peerId": "sender-id", "data": {...} }The server includes several configurable parameters:
This server is designed to run on Val Town and will automatically:
Simply deploy to Val Town and use the provided URL as your signaling server in y-webrtc configuration.
Monitor the server logs and use the /stats endpoint to see:
The web interface at / provides real-time statistics and connection information.