I need an example to connect to socket from froentend
Closed this issue · 7 comments
💬 Questions and Help
Hi,
I tried below code to run socket.
const fastify = require('fastify')()
function handle (conn) {
conn.pipe(conn) // creates an echo server
}
fastify.register(require('fastify-websocket'), {
handle,
options: { maxPayload: 1048576 }
})
fastify.get('/', { websocket: true }, (connection, req) => {
connection.socket.on('message', message => {
// message === 'hi from client'
connection.socket.send('hi from server')
})
})
fastify.listen(3000, err => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
And from my, I connected to my socket by using var test = new WebSocket('ws://localhost:3000')
. How I can trigger /
API with my socket connection. Please help me with some examples.
Does this not work? https://github.com/fastify/fastify-websocket/blob/master/test/router.js#L10-L46.
What library or framework do you use in the frontend?
I can give you the example of vue-native-socket
import VueNativeSock from 'vue-native-websocket';
Vue.use(VueNativeSock, 'ws://localhost:9000/', {
protocol: tokenData, // optional
reconnection: true, // (Boolean) whether to reconnect automatically (false)
reconnectionAttempts: 10, // (Number) number of reconnection attempts before giving up (Infinity),
reconnectionDelay: 6000 // (Number) how long to initially wait before attempting a new (1000)
})
and server
fastify.register(require('fastify-websocket'), {
handle(conn) {
conn.pipe(conn) // creates an echo server
},
options: {
maxPayload: 1048576,
verifyClient(info, next) {
try {
const token = info.req.headers['sec-websocket-protocol']
return next(true)
} catch (err) {
return next(false)
}
}
}
})
fastify.route({
method: 'GET',
url: '/',
handler: (req, reply) => {
reply.send({ route: 'OK' })
},
wsHandler: (conn, req, params) => {
conn.setEncoding('utf8')
conn.on('data', chunk => {
console.log(chunk)
conn.socket.send("Message OK")
})
}
})
I hope it helps you.
I'm sorry that you need something. However, this is open source and I have no bandwidth to help right now.
You can connect from websockets like these :
// Your front end code
// connect to server
const ws = new WebSocket()
// send to server
ws.send('message')
// receive messages
ws.on('message', (message) => {
console.log(message)
})
No matter youre on React, Vue, Angular, or SomeWhatNewJSFramework, the API Of websocket is same take a look here
Thank you guys for your valuable comments. I got it.