Websocket 连接失败消息泛滥

时间:2021-04-06 23:19:42

标签: reactjs websocket socket.io

我对 socket.io 和 socket.io-client 很陌生。 我正在使用这两个 npm 包在两个前端浏览器之间以及通过服务器创建实时数据流。 这是一个 React 项目。

在 React 浏览器运行的某个时刻,Chrome 浏览器上的开发者工具控制台会开始泛滥:enter image description here

我已经调查了其他用户的类似问题,但我还没有找到解决方案。

我使用的是 socket.io 和 socket.io-client 版本 4.0.0。

const uri = process.env.MONGODB_URI;
// connect to db ; async task ; don't listen for requests until connection to db is complete
mongoose.connect(uri, { useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true, useUnifiedTopology: true } )
      .then( (result)=> { //takes in result as parameter to be used as necessary
         console.log('connected to db')
         // listen for requests (assumes use of localhost)
         server.listen(PORT, () => {
            console.log (`listening on *:${PORT}`)
         })
      
         io.on('connection', (socket)=>{
            // console.log('user connected')
         
            socket.on('dispatchlol', msg=>console.log(msg))
            socket.on('mediclol', msg=>console.log(msg))
         
            // relay medic coords to dispatchside
            socket.on('medicCoords', data=>{
               console.log('relay medic coords to dispatchside', JSON.parse(data))
               io.emit('medicCoordsOut', data)
            })
            // relay dispatch choice of unit to dispatchside
            socket.on('offUnit', data=>{
               io.emit('offUnitOut', data)
               console.log('dispatch removed unit:', JSON.parse(data))
            })
            socket.on('onUnit', data=>{
               io.emit('onUnitOut', data)
               console.log('dispatch added unit:', JSON.parse(data))
            })
            // relay availablt units to dispatchside
            // socket.on('availUnits',)
            // initial populate of available units to dispatchside
            socket.on('fetchUnits', () => {
               db.MobileUnit.find({ availability: {$in:["available", "en route to CTAS Alpha-Charlie"]} }).sort({availability: 1}).then(request=>{
                  console.log('fetching available units to dispatchside', request)
                  io.emit('fetchUnitsOut', JSON.stringify(request))
               })
            })
            // relay medic reqs to dispatchside
            socket.on('medReq', data=>{
               console.log('save medic requests to db', JSON.parse(data))
               const medReqpack = JSON.parse(data)
               db.MedReq.create({
                  unit: medReqpack.unit,
                  reqFor: medReqpack.reqFor,
                  status: "active",
               }).then(()=>{
                  db.MedReq.find({status: "active"}).then(request=>{
                     console.log('sending medic reqs to dispatchside', request)
                     io.emit('fetchRequestsOut', JSON.stringify(request))
                  })
               })
            })
            // initial populate of medic requests to dispatchside
            socket.on('fetchRequests', ()=>{
               db.MedReq.find({status: "active"}).then(request=>{
                  console.log('sending medic reqs to dispatchside', request)
                  io.emit('fetchRequestsOut', JSON.stringify(request))
               })
            })
            // db.MedReq.watch().on('change',(change)=>{
            //    console.log('change to medreqs', change)
            // })
            // approve medic req
            socket.on('approveReq', data=>{
               console.log('approve medic requests, dispatchside', JSON.parse(data))
               const handleReq = JSON.parse(data)
               db.MedReq.findOneAndUpdate({
                  unit: handleReq.unit,
                  reqFor: handleReq.isFor,
                  status: "active"
               }, {
                  $set: {
                     status: handleReq.status
                  }
               }).then(()=>{
                  db.MedReq.find({status: "active"}).then(request=>{
                     console.log('sending medic reqs to dispatchside', request)
                     io.emit('fetchRequestsOut', JSON.stringify(request))
                  })
               })
            })
            // reject medic req
            socket.on('rejectReq', data=>{
               console.log('reject medic requests, dispatchside', JSON.parse(data))
               const handleReq = JSON.parse(data)
               db.MedReq.findOneAndUpdate({
                  unit: handleReq.unit,
                  reqFor: handleReq.isFor,
                  status: "active"
               }, {
                  $set: {
                     status: handleReq.status
                  }
               }).then(()=>{
                  db.MedReq.find({status: "active"}).then(request=>{
                     console.log('sending medic reqs to dispatchside', request)
                     io.emit('fetchRequestsOut', JSON.stringify(request))
                  })
               })
            })
            //return request for registered patient name to dispatchside
            socket.on('fetchRegisteredPt', data=>{
               console.log('receiving request for registered Pt info from dispatchside', JSON.parse(data))
               const id = JSON.parse(data)
               db.RegisteredPt.find({id: id.registeredId})
               .then(patient=>{
                  console.log('this is registered patient', patient)
                  io.emit('fetchRegisteredPtOut', JSON.stringify(patient[0]))
               })
            })
            // relay call details to medicside
            socket.on('callDetails', data=>{
               console.log('receiving call details, serverside', JSON.parse(data))
               const callPack = JSON.parse(data)
               const callId = mongoose.Types.ObjectId();
               //save to db
               db.Call.create({
                  _id: callId,
                  deployedUnit: callPack.deployedUnit,      
                  streetDest: callPack.streetDest,
                  cityDest: callPack.cityDest,
                  postalDest: callPack.postalDest,
                  intersection: callPack.intersection,
                  callerName: callPack.callerName,
                  callerNum: callPack.callerNum,
                  destLngLat: callPack.destLngLat,
                  ctas: callPack.ctas,
                  cc: callPack.cc,
                  notes: callPack.notes,
                  police: callPack.police,
                  fire: callPack.fire,
                  registeredPt: callPack.registeredPt
               }).then(()=>{
                  // console.log('thsi is result of saved doc', result)
                  console.log('call details doc id', callId)
                  db.Call.find({_id: callId}).then(doc=>{
                     console.log('sending call details to medicside', doc)
                     io.emit('callDetailsOut', JSON.stringify(doc))
                  })
               })         
            })            
            // find from db active calls
            socket.on('fetchActiveCalls', ()=>{
               db.Call.find({ clearCall: [] }).then(call=>{
                  console.log('sending active calls to dispatchside', call)
                  io.emit('fetchActiveCallsOut', JSON.stringify(call))
               })
            })
            db.Call.watch().on('change', ()=>{
               db.Call.find({ clearCall:[] }).then(call=>{
                  io.emit('fetchActiveCallsOut', JSON.stringify(call))
               })
            })

 
      socket.on("disconnect", (reason) => {
        console.log("user has disconnected :(");
      });
    });
  })
  .catch((err) => {
    console.log(err);
  });

这是一个不会发送的socket.emit代码(点击事件监听器),红色错误信息将开始充斥浏览器控制台:

//one button to rule them all
  const handleSendCall = async (e) => {
    e.preventDefault();

    console.log("sending call details to medicside");
    // turn dest input to coords
    const destLngLat = await getCoords({
      city: city,
      postCode: postal,
      address: street,
    });

    await socket.emit(
      "callDetails",
      JSON.stringify({
        deployedUnit: deployUnits,
        streetDest: street,
        cityDest: city,
        postalDest: postal,
        intersection: intersection,
        callerName: callerName,
        callerNum: callerNum,
        destLngLat: [destLngLat[0], destLngLat[1]],
        ctas: ctas,
        cc: cc,
        notes: notes,
        police: police,
        fire: fire,
        registeredPt: registeredPt,
      })
    );

    setDeployUnits([])
    setStreet("");
    setCity("");
    setIntersection("");
    setPostal("");
    setCallerName("");
    setCallerNum("");
    setCtas("");
    setCC("");
    setNotes("");
    setPolice("");
    setFire("");
    setRegisteredPt("");

    const availunitsTag = document.querySelectorAll('.availunits')
    availunitsTag.forEach((item)=>{
      item.classList.remove('active')
      console.log('actives removed')
    })
  };

0 个答案:

没有答案
相关问题