Premising I'm new to sockets, I'm trying to set up the first configuration on server (Node w/Express).
While doing so, I encountered an issue where nodemon crashes every time I save, by returning Error: listen EADDRINUSE: address already in use :::8080
.
Here the server implementation:
import express from "express";
import cors from "cors";
import { Server, Socket } from "socket.io";
import { createServer } from "http";
import morgan from "morgan";
// App configuration
const app = express();
const server = createServer(app);
const io = new Server(server);
const port = process.env.PORT || 8080;
// Middlewares
app.use(cors());
app.use(express.json());
app.use(morgan("combined"));
// Socket connection
io.on("connect", (socket: Socket) => {
socket.send("test");
});
server.listen(port, () => {
console.log(`Server is up and running on ${process.env.NODE_ENV} - port ${port}`);
});
I would think that happens as the socket.io connection never get closed / disconnected, leaving the server instance up listening.
I had a look around and found many q/a that were suggesting commands to find and kill the process, but I'd need a solution able to disconnect the socket automatically every time the express server gets turned down.
I tried the following:
io.on("disconnect", () => {
io.sockets.disconnect();
}
As suggested here, but TS complains about io.sockets.disconnect()
with a Property 'disconnect' does not exist on type 'Namespace<DefaultEventsMap, DefaultEventsMap>'.ts(2339)
.
Any idea how this should be tackled?