W
Wasp•3mo ago
ArDev

Websocket queries

how does the usewebsocket work? i have in main.wasp webSocket: { fn: import { webSocketFn } from "@src/server/hume/webSocket.js", autoConnect: true }, when i import the socket - import { useWebSocket } from 'wasp/client/webSocket'; exporting - export const webSocketFn = async (io, context) => {
5 Replies
kapa.ai
kapa.ai•3mo ago
Hi @ArDev. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- The useSocket hook provided by Wasp is used to access the WebSocket on the client side. It returns a socket object for sending and receiving events and an isConnected boolean that shows the status of the Socket.IO connection. Wasp automatically connects and establishes a WebSocket connection from the client to the server by default, so you do not need to explicitly call socket.connect() or socket.disconnect(). However, if you set autoConnect: false in your Wasp file, then you should call these as needed. All components using useSocket share the same underlying socket. Here is an example of how you can use the useSocket hook in a React component:
import React, { useState } from 'react'
import {
useSocket,
useSocketListener,
} from 'wasp/client/webSocket'

export const ChatPage = () => {
const [messageText, setMessageText] = useState('')
const [messages, setMessages] = useState([])
const { socket, isConnected } = useSocket()

useSocketListener('chatMessage', logMessage)

function logMessage(msg) {
setMessages((priorMessages) => [msg, ...priorMessages])
}

function handleSubmit(e) {
e.preventDefault()
socket.emit('chatMessage', messageText)
setMessageText('')
}

const messageList = messages.map((msg) => (
<li key={msg.id}>
<em>{msg.username}</em>: {msg.text}
</li>
))
const connectionIcon = isConnected ? '🟢' : '🔴'

return (
<>
<h2>Chat {connectionIcon}</h2>
<div>
<form onSubmit={handleSubmit}>
<div>
<div>
<input
type="text"
value={messageText}
onChange={(e) => setMessageText(e.target.value)}
/>
</div>
<div>
<button type="submit">Submit</button>
</div>
</div>
</form>
<ul>{messageList}</ul>
</div>
</>
)
}
import React, { useState } from 'react'
import {
useSocket,
useSocketListener,
} from 'wasp/client/webSocket'

export const ChatPage = () => {
const [messageText, setMessageText] = useState('')
const [messages, setMessages] = useState([])
const { socket, isConnected } = useSocket()

useSocketListener('chatMessage', logMessage)

function logMessage(msg) {
setMessages((priorMessages) => [msg, ...priorMessages])
}

function handleSubmit(e) {
e.preventDefault()
socket.emit('chatMessage', messageText)
setMessageText('')
}

const messageList = messages.map((msg) => (
<li key={msg.id}>
<em>{msg.username}</em>: {msg.text}
</li>
))
const connectionIcon = isConnected ? '🟢' : '🔴'

return (
<>
<h2>Chat {connectionIcon}</h2>
<div>
<form onSubmit={handleSubmit}>
<div>
<div>
<input
type="text"
value={messageText}
onChange={(e) => setMessageText(e.target.value)}
/>
</div>
<div>
<button type="submit">Submit</button>
</div>
</div>
</form>
<ul>{messageList}</ul>
</div>
</>
)
}
In your main.wasp file, you have defined the WebSocket logic on the server by importing the webSocketFn function from @src/server/hume/webSocket.js. This function should define all the WebSocket events and handlers. Here is an example of how you can define the webSocketFn function:
import { v4 as uuidv4 } from 'uuid'
import { getFirstProviderUserId } from 'wasp/auth'

export const webSocketFn = (io, context) => {
io.on('connection', (socket) => {
const username = getFirstProviderUserId(socket.data.user) ?? 'Unknown'
console.log('a user connected: ', username)

socket.on('chatMessage', async (msg) => {
console.log('message: ', msg)
io.emit('chatMessage', { id: uuidv4(), username, text: msg })
// You can also use your entities here:
// await context.entities.SomeEntity.create({ someField: msg })
})
})
}
import { v4 as uuidv4 } from 'uuid'
import { getFirstProviderUserId } from 'wasp/auth'

export const webSocketFn = (io, context) => {
io.on('connection', (socket) => {
const username = getFirstProviderUserId(socket.data.user) ?? 'Unknown'
console.log('a user connected: ', username)

socket.on('chatMessage', async (msg) => {
console.log('message: ', msg)
io.emit('chatMessage', { id: uuidv4(), username, text: msg })
// You can also use your entities here:
// await context.entities.SomeEntity.create({ someField: msg })
})
})
}
For more information, you can refer to the Wasp documentation on WebSockets (https://wasp-lang.dev/docs/advanced/web-sockets). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, 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?
ArDev
ArDevOP•3mo ago
WebSocketProvider.tsx:18 WebSocket connection to 'ws://localhost:3001/socket.io/?EIO=4&transport=websocket' failed: useAuth.ts:23 GET http://localhost:3001/auth/me net::ERR_CONNECTION_REFUSED socketio-client.js?v=209bf724:1057 WebSocket connection to 'ws://localhost:3001/socket.io/?EIO=4&transport=websocket' failed: useAuth.ts:23 GET http://localhost:3001/auth/me net::ERR_CONNECTION_REFUSED socketio-client.js?v=209bf724:1057 WebSocket connection to 'ws://localhost:3001/socket.io/?EIO=4&transport=websocket' failed: Show 9 more frames @kapa.ai
kapa.ai
kapa.ai•3mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- The error messages you're seeing indicate that the client is unable to establish a connection to the server at localhost:3001. This could be due to several reasons: 1. The server is not running: Ensure that your server is running and listening on port 3001. You can usually do this by running a command like wasp start in your project's root directory. 2. Something else is using port 3001: If something else on your machine is using port 3001, your server won't be able to listen on that port. You can check what's running on that port and stop it, or configure your server to use a different port. 3. Network issues: If you're running the client and server on different machines (or in different Docker containers, different VMs, etc.), they might not be able to reach each other on localhost. You might need to adjust your network settings, use a different hostname, etc. 4. CORS policy: If you're running the client and server on different domains, ports, or protocols, the browser's Same-Origin Policy (https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) will prevent the client from making requests to the server. You can solve this by setting up CORS (Cross-Origin Resource Sharing) (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) on the server. In the context of Wasp, you might need to check your .env configuration files. For example, in .env.server, you should have a line like WASP_WEB_CLIENT_URL=<http://localhost:3000> (or whatever the client's URL is), and in .env.client, you should have a line like REACT_APP_API_URL=<http://localhost:3001> (or whatever the server's URL is). If you're still having trouble, please provide more details about your setup (e.g., are you running this locally or in a production environment? Are you using any kind of virtualization/containerization like Docker or VMs? etc.), and we can give more specific advice. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, 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?
martinsos
martinsos•3mo ago
I will let @miho take a look at this one
miho
miho•3mo ago
Where did you see this error, locally or in a deployed app? Do you see any errors in your server logs?
Want results from more Discord servers?
Add your server