52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import { Server, Socket } from 'socket.io';
|
|
import { createServer } from 'http';
|
|
import express from 'express';
|
|
import cors from 'cors';
|
|
|
|
const app = express();
|
|
app.use(cors());
|
|
|
|
const httpServer = createServer(app);
|
|
const io = new Server(httpServer, {
|
|
cors: {
|
|
origin: [
|
|
"http://localhost:3000",
|
|
"http://localhost:3030",
|
|
"http://localhost:3031",
|
|
"https://dev.duelfi.io",
|
|
"https://beta.duelfi.io"
|
|
],
|
|
methods: ["GET", "POST"]
|
|
}
|
|
});
|
|
|
|
// Store recent messages in memory (you might want to use a database in production)
|
|
const recentMessages: any[] = [];
|
|
const MAX_MESSAGES = 100;
|
|
|
|
io.on('connection', (socket: Socket) => {
|
|
console.log('User connected:', socket.id);
|
|
|
|
// Send recent messages to newly connected users
|
|
socket.emit('recent messages', recentMessages);
|
|
|
|
socket.on('chat message', (message: any) => {
|
|
// Add message to recent messages
|
|
recentMessages.push(message);
|
|
if (recentMessages.length > MAX_MESSAGES) {
|
|
recentMessages.shift();
|
|
}
|
|
|
|
// Broadcast message to all connected clients
|
|
io.emit('chat message', message);
|
|
});
|
|
|
|
socket.on('disconnect', () => {
|
|
console.log('User disconnected:', socket.id);
|
|
});
|
|
});
|
|
|
|
const PORT = 3040;
|
|
httpServer.listen(PORT, () => {
|
|
console.log(`Socket.IO server running on port ${PORT}`);
|
|
});
|