O
O
Ostap Likhodeev2019-09-24 11:58:22
Node.js
Ostap Likhodeev, 2019-09-24 11:58:22

Why don't messages come from websocket?

Why do not messages come to the console from the socket? Everything works fine in the server console. And the browser is empty. And from the connection event it comes to the browser. What's the matter?
Server:

const express = require('express'),
  app = express(),
  http = require('http').createServer(app),
  io = require('socket.io')(http)

const host = '127.0.0.1'
const port = 8080

let clients = []

io.on('connection', socket => {
  console.log({'connected':`${socket.id}`})
  clients.push(socket.id)
  socket.emit('message', {"imid":`${socket.id}`})
  socket.on('message', message => console.log( message))

  socket.on('disconnect', () => {
    clients.splice(clients.indexOf(socket.id), 1)
    console.log({"discconnected":`${socket.id}`})
  })
})

app.use(express.static(__dirname))

app.get('/', (req, res) => res.render('index'))

app.get('/clients-count', (req, res) => {
  res.json({ count: io.clients().server.engine.clientsCount })
})

app.post('/client/:id', (req, res) => {
  if (clients.indexOf(req.params.id) !== -1) {
    io.sockets.connected[req.params.id].emit('private message', `Message to client with id ${req.params.id}`)
    return res.status(200).json({ message: `Message was sent to client with id ${req.params.id}` })
  } else return res.status(404).json({ message: 'Client not found' })
})

http.listen(port, host, () => console.log(`Server listens http://${host}:${port}`))

Customer:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Socket.io example</title>
    <script src="/node/node_modules/socket.io-client/dist/socket.io.js"></script>
    <script>
      let socket = io('http://127.0.0.1:8080')

      
      socket.on('private message', message => console.log('Private message from server: ', message))
    socket.on('message', message => console.log('Message: ', message))

      function sendMessageToServer() {
        socket.emit('message', "I'm client")		
      }
    </script>
  </head>
  <body>
    <button onclick="sendMessageToServer()">Send</button>
  </body>
</html>

Why does everything work when the send button is pressed in the server console, but the browser console is empty?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question