73 lines
1.8 KiB
JavaScript
73 lines
1.8 KiB
JavaScript
/**
|
|
* WebSocket handler for this drop
|
|
*
|
|
* Connect to: ws://localhost:3001/ws/<drop-name>
|
|
*
|
|
* The WebSocket handler provides real-time bidirectional communication.
|
|
* Use ws.publish(dropName, message) to broadcast to all connected clients.
|
|
*/
|
|
export const websocket = {
|
|
/**
|
|
* Called when a client connects
|
|
* @param {ServerWebSocket} ws - The WebSocket connection
|
|
*/
|
|
open(ws) {
|
|
console.log('Client connected')
|
|
|
|
// Send welcome message
|
|
ws.send(JSON.stringify({
|
|
type: 'connected',
|
|
message: 'Welcome to DROPNAME!'
|
|
}))
|
|
},
|
|
|
|
/**
|
|
* Handle incoming messages
|
|
* @param {ServerWebSocket} ws - The WebSocket connection
|
|
* @param {string|Buffer} message - The message received
|
|
*/
|
|
message(ws, message) {
|
|
try {
|
|
const data = JSON.parse(message)
|
|
console.log('Received message:', data)
|
|
|
|
// Echo the message back
|
|
ws.send(JSON.stringify({
|
|
type: 'echo',
|
|
data: data
|
|
}))
|
|
|
|
// Broadcast to all connected clients on this drop's channel
|
|
// ws.publish('DROPNAME', JSON.stringify({
|
|
// type: 'broadcast',
|
|
// data: data
|
|
// }))
|
|
|
|
} catch (error) {
|
|
console.error('Error parsing message:', error)
|
|
ws.send(JSON.stringify({
|
|
type: 'error',
|
|
message: 'Invalid JSON'
|
|
}))
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Called when connection is closed
|
|
* @param {ServerWebSocket} ws - The WebSocket connection
|
|
* @param {number} code - Close code
|
|
* @param {string} reason - Close reason
|
|
*/
|
|
close(ws, code, reason) {
|
|
console.log(`Client disconnected: ${code} ${reason}`)
|
|
},
|
|
|
|
/**
|
|
* Called when there's an error
|
|
* @param {ServerWebSocket} ws - The WebSocket connection
|
|
* @param {Error} error - The error
|
|
*/
|
|
error(ws, error) {
|
|
console.error('WebSocket error:', error)
|
|
}
|
|
}
|