Search code examples
javascriptnode.jsserversocket.ioclient

Server is not responding when client is trying to connect to it


I'm new to Socket.io. I'm trying to establish a connection to the server. But the connection event is not responding. Is there anything I'm doing wrong that I am unable to figure out? Here is my code for the server and client side.

client.html

<script src="http://localhost:5000/socket.io/socket.io.js">
    const io = require('socket.io-client');
    const socket = io.connect("https://localhost:5000");
    socket.on("connect", () => {
        console.log(socket.id);
    });
</script>

server.js

const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on("connection", (socket) => {
    console.log(socket.id);
  });
server.listen(5000,()=>{
    console.log("Server is listening at port 5000...");
})

Solution

  • You did not provide any error messages which makes it incredibly hard to help you. Usually, if you work with Code you wrote for the Browser you can debug/see errors with the Browser Console (Which usually opens once you open F12). I recommend you for the next post to provide some information on the errors you are getting.

    The possible errors I can think of in your code:

    1. Split SocketIoClient Script Tag and Execution Tag. Since you put src at the source Tag the code inside the tag will not run at all. try something like this:
        <script src="yourSocketIoLocation/socket.io.min.js"></script>
        <script>
          const socket = io.connect("http://localhost:5000");
          socket.on("connect", () => {
              console.log(socket.id);
          });
         </script>
    
    1. Require doesn't actually work in Clientside Javascript it only works in NodeJs and in this case you actually don't even need it. As you can see in the above Example I just removed it and it should work. An Error: Uncaught ReferenceError: require is not defined should not show up again.

    2. CORS. Your Server Code looks fine, but for it to work I had to add CORS Settings like this:

    const app = require('express')();
    const server = require('http').createServer(app);
    const io = require('socket.io')(server, {
      cors: {
        origin: "http://127.0.0.1:8080",
        methods: ["GET", "POST"]
      }
    });
    io.on("connection", (socket) => {
        console.log(socket.id);
      });
    server.listen(5000,()=>{
        console.log("Server is listening at port 5000...");
    })
    

    You can find documentation on the cors Settings here: https://socket.io/docs/v3/handling-cors/ Just swap the http://127.0.0.1:8080 with your actual webserver location.