V
V
vlad17532021-12-29 22:14:21
JavaScript
vlad1753, 2021-12-29 22:14:21

How to solve the problem with WebSockets?

Greetings.

A very strange situation. This is my first time using web sockets.
When the page loads, the client sends a request to the server.
The strange thing is that when the page is first loaded, the connection event on the backend fires 2 times.
Second reboot - 3 times
Third - 4 times

Video: https://www.recordjoy.com/view/V40Nzn77pFoShjC8O4H7

What is the reason???

Customer:

const ws = new WebSocket('ws://localhost:8080')

const id = window.location.pathname.split('/')[2]

ws.onopen = () => {
        
    const message = {
        event: "transition",
        id
    }

    ws.send(JSON.stringify(message))

}

ws.onmessage = (message) => {
    console.log(message.data)
}

ws.onerror = (err) => {
    console.log(err)
}

window.onbeforeunload = () => {
    ws.close()
}


Server (this is the middleware in express):

import { WebSocketServer } from 'ws'
import linkService from '../services/link.js'
import transitionService from '../services/transition.js'


const wss = new WebSocketServer({ port: 8080 })

export default function(req, res, next){


 
    wss.on('connection', ws => {
        console.log('connection')
        
        if(req.autorized){
            ws.clientID = req.user._id
        }

        
        ws.on('message', async (message)=>{

            const data = JSON.parse(message.toString())


            switch (data.event) {
                case "transition":
                    const linkData = await linkService.saveFollowData(req.socket.remoteAddress, req.get('user-agent'), data.id)
                    wss.clients.forEach(c => {
                        if(c.clientID == linkData.user){
                            transitionService.getData(linkData.user).then((data)=>{
                                c.send(JSON.stringify(data))
                            })
                        }
                    })
                    ws.send(linkData.from)
                    break;
            
                default:
                    break;
            }
        })
    })
    next()
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-12-29
@vlad1753

You subscribe to a websocket connection for every http request that is processed by your middleware, thereby producing handlers.
Your websocket has nothing to do with http at all and sits on a separate port.
If desired, by the way, you can reuse the http server instance for both express and websocket, then they will be on the same port.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question