AlarmClockMan
AlarmClockMan

Reputation: 458

socket.io "connection" event isn't being called

I am trying to create a very simple server with express and socket.io. When I open the webpage (at localhost:2000), I can see the HTML file, but the io.sockets.on("connection") event is not called and I don't see "socket connection" in the console.

app.js:

var express = require("express");
var app = express();
var serv = require("http").Server(app);

app.get("/",function(req, res) {
  res.sendFile(__dirname + "/client/index.html");
});
app.use("/client", express.static(__dirname + "/client"));

serv.listen(2000)

var io = require("socket.io")(serv,{});
io.sockets.on("connection", function(socket) {
  console.log("socket connection")
});

index.html:

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
</script>

I previously installed express and socket.io through npm.

How can I fix this? I'm running node.js v12.13.1, express 6.12.1, and socket.io 6.12.1 on macOS 11.1

Upvotes: 0

Views: 56

Answers (1)

AlarmClockMan
AlarmClockMan

Reputation: 458

Just figured this out. The CDN I had used was outdated.

In index.html, I replaced

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

with

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.0/socket.io.js"></script>

Upvotes: 1

Related Questions