nakama/backend/websocket.js

77 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { Server } = require('socket.io');
const config = require('./config');
const Notification = require('./models/Notification');
let io = null;
// Инициализация WebSocket сервера
function initWebSocket(server) {
const corsOrigin = config.corsOrigin === '*' ? '*' : config.corsOrigin.split(',');
io = new Server(server, {
cors: {
origin: corsOrigin,
methods: ['GET', 'POST'],
credentials: true
},
transports: ['websocket', 'polling'], // Поддержка обоих транспортов
pingTimeout: 60000,
pingInterval: 25000
});
io.on('connection', (socket) => {
console.log(`✅ WebSocket подключен: ${socket.id}`);
// Присоединиться к комнате пользователя
socket.on('join', (userId) => {
socket.join(`user_${userId}`);
console.log(`Пользователь ${userId} присоединился к комнате`);
});
// Отключение
socket.on('disconnect', () => {
console.log(`❌ WebSocket отключен: ${socket.id}`);
});
});
console.log('✅ WebSocket сервер инициализирован');
return io;
}
// Отправить уведомление пользователю в real-time
function sendNotification(userId, notification) {
if (io) {
io.to(`user_${userId}`).emit('notification', notification);
}
}
// Отправить обновление поста
function sendPostUpdate(postId, data) {
if (io) {
io.emit('post_update', { postId, ...data });
}
}
// Отправить новый комментарий
function sendNewComment(postId, comment) {
if (io) {
io.emit('new_comment', { postId, comment });
}
}
// Отправить информацию о том, кто онлайн
function broadcastOnlineUsers(users) {
if (io) {
io.emit('online_users', users);
}
}
module.exports = {
initWebSocket,
sendNotification,
sendPostUpdate,
sendNewComment,
broadcastOnlineUsers
};