W
Wasp•2mo ago
NEROX

Web socket for streaming

Create an example of web socket for streaming
4 Replies
kapa.ai
kapa.ai•2mo ago
Hi @NEROX. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To create an example of WebSocket for streaming in Wasp, we can use the built-in WebSocket support. Here's a step-by-step guide to set up a basic streaming example: 1. First, enable WebSockets in your Wasp file:
app todoApp {
// ...

webSocket: {
fn: import { webSocketFn } from "@src/webSocket",
autoConnect: true,
},
}
app todoApp {
// ...

webSocket: {
fn: import { webSocketFn } from "@src/webSocket",
autoConnect: true,
},
}
2. Define the WebSocket server logic in src/webSocket.ts:
import { type WebSocketDefinition, type WaspSocketData } from 'wasp/server/webSocket'

export const webSocketFn: WebSocketFn = (io, context) => {
io.on('connection', (socket) => {
console.log('A user connected')

// Simulate streaming data
let counter = 0
const streamInterval = setInterval(() => {
socket.emit('streamData', { count: counter++ })
}, 1000)

socket.on('disconnect', () => {
console.log('User disconnected')
clearInterval(streamInterval)
})
})
}

type WebSocketFn = WebSocketDefinition<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>

interface ServerToClientEvents {
streamData: (data: { count: number }) => void;
}

interface ClientToServerEvents {}

interface InterServerEvents {}

interface SocketData extends WaspSocketData {}
import { type WebSocketDefinition, type WaspSocketData } from 'wasp/server/webSocket'

export const webSocketFn: WebSocketFn = (io, context) => {
io.on('connection', (socket) => {
console.log('A user connected')

// Simulate streaming data
let counter = 0
const streamInterval = setInterval(() => {
socket.emit('streamData', { count: counter++ })
}, 1000)

socket.on('disconnect', () => {
console.log('User disconnected')
clearInterval(streamInterval)
})
})
}

type WebSocketFn = WebSocketDefinition<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>

interface ServerToClientEvents {
streamData: (data: { count: number }) => void;
}

interface ClientToServerEvents {}

interface InterServerEvents {}

interface SocketData extends WaspSocketData {}
3. Use the WebSocket on the client side in a React component:
import React, { useState, useEffect } from 'react'
import { useSocket, useSocketListener } from 'wasp/client/webSocket'

export const StreamingPage = () => {
const [streamData, setStreamData] = useState<number | null>(null)
const { isConnected } = useSocket()

useSocketListener('streamData', (data) => {
setStreamData(data.count)
})

const connectionIcon = isConnected ? '🟢' : '🔴'
return (
<>
<h2>Streaming Data {connectionIcon}</h2>
<div>
{streamData !== null ? (
<p>Received count: {streamData}</p>
) : (
<p>Waiting for data...</p>
)}
</div>
</>
)
}
import React, { useState, useEffect } from 'react'
import { useSocket, useSocketListener } from 'wasp/client/webSocket'

export const StreamingPage = () => {
const [streamData, setStreamData] = useState<number | null>(null)
const { isConnected } = useSocket()

useSocketListener('streamData', (data) => {
setStreamData(data.count)
})

const connectionIcon = isConnected ? '🟢' : '🔴'
return (
<>
<h2>Streaming Data {connectionIcon}</h2>
<div>
{streamData !== null ? (
<p>Received count: {streamData}</p>
) : (
<p>Waiting for data...</p>
)}
</div>
</>
)
}
This example demonstrates a simple streaming scenario where the server sends a counter value to the client every second. The client displays the received data in real-time. For more detailed information on using WebSockets in Wasp, you can refer to the WebSockets documentation. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @NEROX, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
NEROX
NEROXOP•2mo ago
@kapa.ai [ Wasp ] ext-src/operations.ts(148,24): error TS2339: Property 'webSocket' does not exist on type '{ entities: { DeepSeekChat: DeepSeekChatDelegate<DefaultArgs>; DeepSeekMessage: DeepSeekMessageDelegate<DefaultArgs>; }; user?: AuthUser; }'. Line 148: // Get the WebSocket server instance const io = context.webSocket;
kapa.ai
kapa.ai•2mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Based on the error message you've provided, it seems you're trying to access context.webSocket in your operations file, but this property doesn't exist on the context object. This is a known limitation in Wasp's current implementation of WebSockets. According to the GitHub issue about using WebSocket server inside server-side code, the WebSocket server instance (io) is not directly exposed or documented for use outside of the WebSocket initialization function. However, there is a workaround that you can use. As mentioned in a comment on that GitHub issue: 1. Create a global variable in the file where you have your WebSocket initialization function. 2. Set this global variable to the io instance inside the initialization function. 3. Export this global variable. 4. Import and use this exported variable in other parts of your server-side code where you need access to the WebSocket instance. Here's how you can implement this workaround: 1. In your src/webSocket.ts file (or wherever you define your webSocketFn):
import { Server } from 'socket.io';

let ioInstance: Server | undefined;

export const webSocketFn = (io, context) => {
ioInstance = io;
// ... rest of your WebSocket initialization code
}

export { ioInstance };
import { Server } from 'socket.io';

let ioInstance: Server | undefined;

export const webSocketFn = (io, context) => {
ioInstance = io;
// ... rest of your WebSocket initialization code
}

export { ioInstance };
2. Then in your operations.ts file:
import { ioInstance } from './webSocket';

// ... your operation code

// Instead of context.webSocket, use:
const io = ioInstance;

// Now you can use 'io' for WebSocket operations
import { ioInstance } from './webSocket';

// ... your operation code

// Instead of context.webSocket, use:
const io = ioInstance;

// Now you can use 'io' for WebSocket operations
This workaround allows you to access the WebSocket server instance outside of the initialization function. However, keep in mind that this is not an ideal solution, and the Wasp team is aware of this limitation. They are working on providing better first-party support for this use case in the future. For the most up-to-date information on this issue, you can follow the progress on the GitHub issue. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @NEROX, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
NEROX
NEROXOP•2mo ago
Love you Kapa

Did you find this page helpful?