WebSocket Server
Why we will use socket.io
β
If you want to configure CORS for your Socket.io server without using additional packages like cors
, you can directly configure it within the socketio
initialization options.
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
// Configure Socket.io with CORS
const io = new Server(server, {
cors: {
origin: "https://localhost:3000", // Allow from specific origin
methods: ["GET", "POST"] // Allow only GET and POST methods
}
});
// Socket.io connection handling
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('User disconnected');
});
// Example: Handle incoming messages
socket.on('chat message', (msg) => {
console.log('Message received: ' + msg);
io.emit('chat message', msg); // Broadcast message to all connected clients
});
});
// Start server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Explanation:β
-
Socket.io Server Initialization:
- Instead of importing
socket.io
, we're using{ Server }
fromsocket.io
. This allows us to directly configure the server options when creating the instance.
- Instead of importing
-
CORS Configuration:
- The
cors
option withinServer
constructor allows specifying CORS settings. origin
: Specifies the allowed origin. In this example, it allows requests fromhttps://localhost:3000
.methods
: Specifies the allowed HTTP methods. Here, onlyGET
andPOST
methods are allowed.
- The
-
Socket.io Connection Handling:
- Handles socket connections (
io.on('connection', ...)
) and disconnections (socket.on('disconnect', ...)
). - Includes an example of handling incoming messages (
socket.on('chat message', ...)
), echoing them back to all clients (io.emit('chat message', ...)
).
- Handles socket connections (
-
Server Startup:
- Starts the HTTP server (
server.listen(...)
), specifying the port number (PORT
) to listen on.
- Starts the HTTP server (
This setup allows you to control CORS directly within the Socket.io server configuration, without needing additional middleware like cors
. Adjust the origin
and methods
as per your specific requirements. Remember to handle client-side connections and events accordingly in your frontend application.
Documentationβ
- How to connect and use the
socket.io
please visit at Socket.io Docs