简体   繁体   中英

Why am I not getting any response from socket.io connection event

I have just started with socket.io and to practice I wanted to create a server whose output tells me 'A user connected' every time a connection with the client is established. I thought that a connection is established just by starting the server and going to localhost:5000 . After that I would see the output message from the connection in my console.

 const express = require('express') const app = express() app.get('/', (req, res) => { res.send('I am alive') }) PORT = process.env.PORT || 5000 const server = app.listen( PORT, () =>{ console.log(`Listening to http://localhost:${PORT}`)}) const io = require('socket.io')(server) io.on('connection', function(socket) { console.log('A user connected');})

For this process, I type node server.js , wait until the message Listening to http://localhost:5000 appears and then I go to the page. But when I navigate to the page I see no console message. Is a html file necessary for the message to appear? Or am I not seeing a important step? I have seen some tutorials but all of them use a html file, and I wanted to avoid that step. Thanks a lot!

On server by writing this code

io.on('connection', function(socket) {
     console.log('A user connected');
 })

you are listening to the connection and somebody, somewhere has to connect to the socket of this server on same url as your server is for example like this

var socket = require('socket.io-client')('http://localhost:5000');
socket.on('connect', function () {
     socket.on("FromAPI", data => {
        setResponse(data);
     });
     socket.emit("FromAPI")
 }

When you make socket connection anywhere either in html or any other code the console.log() will print data on server

The code you shared is the server end you need to setup client as well.

Client End:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script>
    var socket = io('http://localhost:<PORT>');
</script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM