Quei
Quei
Explore posts from servers
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
in ultra short this is the principle
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
No description
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
And of course, the name and path of server\api\websocket.ts will also be changed! 🙂
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
No, no, you got me completely right... I couldn't figure out how to reuse the connection from server\api\websocket.ts, so I just created a new "client" to send the messages. In a later stage, server\api\websocket.ts will be secured so that only the server can send messages. The browser will also connect to server\api\websocket.ts, but it will only be the consumer of the messages in the end. And this will be the baseline for my reactivity—when something changes in the backend, I'll notify all consumers to update via a regular API call.
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
Well, this is only a partial solution.
In the plugin, I open the connection with wsConnect(), and in my services on the server side, I use the connection with wsSendOnce("bla bla bla").
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
Additionally, I use a plugin to open one connection, and after that, I can use wsSend everywhere on the server side. F***ing awesome!
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
// Function to send a message
export const wsSend = (message: string) => {
if (ws && ws.readyState === WebSocket.OPEN) {
console.log('sending message...', message)
ws.send(message)
} else {
console.error('WebSocket is not open. Cannot send message:', message)
}
}

// Function to send a ping message
export const ping = () => {
if (ws && ws.readyState === WebSocket.OPEN) {
console.log('ws', 'Sending ping')
ws.send('ping')
} else {
console.error('WebSocket is not open. Cannot send ping.')
}
}

// Function to connect, send a message, and disconnect
export const wsSendOnce = async (message: string) => {
if (ws && ws.readyState === WebSocket.OPEN) {
wsSend(message)
} else {
await wsConnect()
wsSend(message)
}
}
// Function to send a message
export const wsSend = (message: string) => {
if (ws && ws.readyState === WebSocket.OPEN) {
console.log('sending message...', message)
ws.send(message)
} else {
console.error('WebSocket is not open. Cannot send message:', message)
}
}

// Function to send a ping message
export const ping = () => {
if (ws && ws.readyState === WebSocket.OPEN) {
console.log('ws', 'Sending ping')
ws.send('ping')
} else {
console.error('WebSocket is not open. Cannot send ping.')
}
}

// Function to connect, send a message, and disconnect
export const wsSendOnce = async (message: string) => {
if (ws && ws.readyState === WebSocket.OPEN) {
wsSend(message)
} else {
await wsConnect()
wsSend(message)
}
}
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
Okay, I figured it out... my issue is solved. I created a utility with this content:
let ws
const reconnectInterval = 5000 // Time in ms to wait before attempting to reconnect
let isManuallyClosed = false // Flag to prevent reconnection when connection is manually closed

// Function to handle WebSocket connection
export const wsConnect = async () => {
const isSecure = process.env.SITE_PROTOCOL === 'https'
const url = (isSecure ? 'wss://' : 'ws://') + process.env.SITE_NAME + '/api/websocket'

// Close existing connection if present
if (ws) {
console.log('ws', 'Closing previous connection before reconnecting...')
wsClose()
}

console.log('ws', 'Connecting to', url, '...')
ws = new WebSocket(url)

// Wait for the WebSocket to open
await new Promise((resolve) => ws.addEventListener('open', resolve))

console.log('ws', 'Connected!')

// Handle connection close
ws.addEventListener('close', handleWsClose)

// Handle connection errors
ws.addEventListener('error', handleWsError)
}

// Function to handle WebSocket closure
const handleWsClose = () => {
console.log('ws', 'Connection closed.')
if (!isManuallyClosed) {
console.log('ws', `Attempting to reconnect in ${reconnectInterval / 1000} seconds...`)
setTimeout(wsConnect, reconnectInterval) // Attempt to reconnect after delay
}
}

// Function to handle WebSocket errors
const handleWsError = (error: any) => {
console.error('ws', 'Connection error:', error)
ws.close() // Close and trigger the reconnection logic
}

// Function to manually close the WebSocket connection
export const wsClose = () => {
if (ws && ws.readyState === WebSocket.OPEN) {
console.log('ws', 'Manually closing the connection...')
isManuallyClosed = true
ws.close()
} else {
console.log('ws', 'Connection is already closed.')
}
}
let ws
const reconnectInterval = 5000 // Time in ms to wait before attempting to reconnect
let isManuallyClosed = false // Flag to prevent reconnection when connection is manually closed

// Function to handle WebSocket connection
export const wsConnect = async () => {
const isSecure = process.env.SITE_PROTOCOL === 'https'
const url = (isSecure ? 'wss://' : 'ws://') + process.env.SITE_NAME + '/api/websocket'

// Close existing connection if present
if (ws) {
console.log('ws', 'Closing previous connection before reconnecting...')
wsClose()
}

console.log('ws', 'Connecting to', url, '...')
ws = new WebSocket(url)

// Wait for the WebSocket to open
await new Promise((resolve) => ws.addEventListener('open', resolve))

console.log('ws', 'Connected!')

// Handle connection close
ws.addEventListener('close', handleWsClose)

// Handle connection errors
ws.addEventListener('error', handleWsError)
}

// Function to handle WebSocket closure
const handleWsClose = () => {
console.log('ws', 'Connection closed.')
if (!isManuallyClosed) {
console.log('ws', `Attempting to reconnect in ${reconnectInterval / 1000} seconds...`)
setTimeout(wsConnect, reconnectInterval) // Attempt to reconnect after delay
}
}

// Function to handle WebSocket errors
const handleWsError = (error: any) => {
console.error('ws', 'Connection error:', error)
ws.close() // Close and trigger the reconnection logic
}

// Function to manually close the WebSocket connection
export const wsClose = () => {
if (ws && ws.readyState === WebSocket.OPEN) {
console.log('ws', 'Manually closing the connection...')
isManuallyClosed = true
ws.close()
} else {
console.log('ws', 'Connection is already closed.')
}
}
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
I’m also a bit puzzled when I read this. It should actually be global according to how it’s used, but I need to test it. It’s clearly stated here that it’s global: https://nuxt-socket-io.netlify.app/usage/
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
If I take a look at this guide:
https://socket.io/how-to/use-with-nuxt It looks like it's exactly what I was searching for. I just need to trigger socket.emit("blabla").
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
Sure, but it gives me ideas, and after a bit of research, I can decide which way I want to go.
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
ChatGPT is suggesting using WebSockets or SSE, but I’ve never used SSE before.
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
With the alternative using sockets, for example, I don’t need to worry about cleaning up entries, and I also don’t really need to care about who is connected and who isn’t (which I think is similar to KV). I can simply send a message to consumers, and it’s not permanent, meaning I don’t have to clean it up after sending or setting something.
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
Hmm, you’re using a temporary store and all consumers will read from there. Isn’t that kind of an ugly solution? Then I’d also need to delete the entries from time to time, and the frontend would need extra logic to handle that too. I did something similar in the past with Socket.io, and I was hoping to use a built-in feature in Nuxt this time. If I can’t figure out how to do this, I’ll need to install the Socket.io package again.
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
I think we're not talking about the same thing! 🙂 I adapted the example from here:
https://stackblitz.com/edit/nitro-web-sockets-fmeygr?file=server%2Fservice%2Fmail%2FparseEmail.ts I hope this example makes things clearer! I know how to send and react to messages inside _ws.ts, but I’m unsure how to reuse this to send a message from another component to the same "room." I created service/mail/parseEmail.ts to clarify what I want to do. As a test, I simply created a function that logs a message every 10 seconds, and // message('newMail') ??? is a placeholder where it should send something to all peers. Hopefully, this makes the problem clearer! It would be awesome if you could replace the placeholder with something that works 😄
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
Maybe the better question is: how do I send a message?
I can import the message from server\api\websocket.ts, but how do I send it to all peers?
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
The plan was to use WebSockets for this since a chat feature will also be added later.
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
If by "dedicated message bus" you mean a topic where the "clients" (in this case, the frontend) subscribe, then yes, that's exactly what I'm trying to do. The example above is just a quick and dirty implementation to see if it would work in my existing project—and yes, it does! Now, I’m at the stage where I want to implement the WebSockets more cleanly.
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
What do you mean by KV or a dedicated message bus? can you send me an example?
49 replies
NNuxt
Created by Quei on 10/14/2024 in #❓・help
Reusable websocket component
This is exactly where I’m struggling... I’m not sure how to properly extract this so that it works in the end.
49 replies