Веб-сокет не уведомляет отправителя или получателя, когда запрос на добавление в друзья принятAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Веб-сокет не уведомляет отправителя или получателя, когда запрос на добавление в друзья принят

Сообщение Anonymous »

Я запускаю свой веб-сокет на сервере node.js и приложение для Android в котлине, и я сопоставляю пользователей в веб-сокете по имени пользователя, чтобы уведомить их. У меня есть функция sendchatmessage, которая правильно уведомляет как отправителя, так и получателя, поэтому я могу отправлять сообщения обратно и вперед, и они проходят нормально, но моя функция handleacceptfriend не уведомляет ни отправителя, ни получателя.
Когда она отправляет обратно идентификатор, соответствующий строке запроса на добавление в друзья, и она меняет " решение» на 1 (принято), он правильно обновляет таблицу списка друзей, но просто не уведомляет ни sendTo, ни SentFrom. Я думаю, что это как-то связано с выборкой sendTo и SentFrom, которая существует только потому, что каким-то образом в sendTo и SentFrom помещено значение «не определено», поэтому я думаю, что мне придется изменить его на стороне клиента, чтобы взять имя пользователя клиента (получатель) и и друг запрашивает имя пользователя (отправителя) и отправляет его в функцию, чтобы я не получил неопределенное значение, но ничего не работает, в любом случае, даже если выборка sendTo и sendFrom не уведомляет ни отправителя, ни получателя по какой-то неизвестной причине. У меня такое чувство, что я упускаю что-то глупое, но я новичок в веб-сокетах и ​​разработке Android. Я занимаюсь этим всего 3 месяца.
Подключено к базе данных
Аутентификация прошла успешно
Друг запрос с идентификатором 3 принят
robtest3 уже является другом robtest1
robtest1 уже является другом robtest3
Не найдено соединение WebSocket для robtest1
(только 1 не получает их, но ни одно устройство не получает тип сообщения, полученного на стороне клиента)

Код: Выделить всё

async function sendChatMessage(message, ws, wsId) {
try {
console.log('Received message for sending chat message:', message);

const { sender, receiver, messageText, authToken } = message; // Ensure messageText is correctly parsed
console.log('Extracted sender:', sender, 'receiver:', receiver, 'message:', messageText);

// Check if sender, receiver, and messageText are valid
if (!sender || !receiver || !messageText) {
throw new Error('Sender, receiver, or message text is empty or undefined');
}

const connection = await connectToDatabase();
console.log('Connected to database');

// Query to check authToken and TokenExpiry in Users table
const authQuery = `
SELECT AuthToken, TokenExpiry
FROM Users
WHERE AuthToken = ? AND TokenExpiry > NOW()
`;
const [authResults] = await executeQuery(connection, authQuery, [authToken]);

// If no rows returned or token expired, send auth_failed message
if (!authResults || authResults.length === 0) {
ws.send(JSON.stringify({ type: 'Auth_Failed', message: 'Authentication failed' }));
console.log('Sent Auth_Failed response to client');
connection.end(); // Close database connection
return;
}

// Insert the chat message into the Messages table
const insertMessageQuery = `
INSERT INTO Messages (Sender, Receiver, Message)
VALUES (?, ?, ?)
`;
await executeQuery(connection, insertMessageQuery, [sender, receiver, messageText]);
console.log('Inserted message into Messages table');

// Send success message to the sender
ws.send(JSON.stringify({ type: 'sendchatmessagesuccess', sender, messageText }));
console.log('Sent sendchatmessagesuccess response to client (sender)');

// Optionally, if the receiver is online, send the message to the receiver
const receiverWsId = Object.keys(userSocketMap).find(key => userSocketMap[key] === receiver);
if (receiverWsId && connections[receiverWsId]) {
connections[receiverWsId].send(JSON.stringify({ type: 'sendchatmessagesuccess', sender, messageText }));
console.log('Sent newmessage response to receiver');
}

// Close the database connection
connection.end();
console.log('Closed database connection');
} catch (error) {
console.error('Error handling send chat message:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Failed to send chat message' }));
}
}

Код: Выделить всё

const https = require('https');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
const mysql = require('mysql');
const { v4: uuidv4 } = require('uuid');

// Load SSL key and certificate
const privateKey = fs.readFileSync('key.key', 'utf8');
const certificate = fs.readFileSync('certificate.crt', 'utf8');
const credentials = { key: privateKey, cert: certificate };

const server = https.createServer(credentials, (req, res) => {
if (req.url === '/' || req.url === '/index.html') {
const htmlPath = path.join(__dirname, 'index.html');
fs.readFile(htmlPath, (err, data) =>  {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
} else {
res.writeHead(404);
res.end('Not Found');
}
});

const wss = new WebSocket.Server({ server });
const connections = {};
const userSocketMap = {};

// Database connection configuration
const dbConfig = {
host: '*********************************************************.eu-west-2.rds.amazonaws.com',
user: '************',
password: '***********',
database: 'chatlink_schema'
};

// Function to connect to MySQL database using async/await
async function connectToDatabase() {
const connection = mysql.createConnection(dbConfig);

await new Promise((resolve, reject) => {
connection.connect((err) => {
if (err) {
reject(err);
return;
}
console.log('Connected to MySQL database');
resolve();
});
});

return connection;
}

// Function to execute a query and return results
function executeQuery(connection, query, values) {
return new Promise((resolve, reject) => {
connection.query(query, values, (error, results) => {
if (error) {
reject(error);
return;
}
resolve(results);
});
});
}

// WebSocket server handling
wss.on('connection', (ws) => {
console.log('WebSocket connection opened');

// Generate a unique WebSocket ID
const wsId = uuidv4();
connections[wsId] = ws; // Store WebSocket connection using the generated ID

// Handle incoming messages from clients
ws.on('message', async (data) =>  {
try {
const message = JSON.parse(data);
console.log('Received message:', message);

// Check message type and handle accordingly
if (message.type === 'register') {
handleRegistration(message, ws, wsId);
} else if (message.type === 'login') {
handleLogin(message, ws, wsId);
} else if (message.type === 'registerwsid') {
registerWSID(message, ws, wsId);
} else if (message.type === 'getfriendslist') {
handleFriendsList(message, ws, wsId);
} else if (message.type === 'addfriend') {
addFriend(message, ws, wsId);
} else if (message.type === 'getfriendrequests') {
getFriendRequests(message, ws, wsId);
} else if (message.type === 'acceptfriend') {
handleAcceptFriend(message, ws, wsId);
} else if (message.type === 'declinefriend') {
handleDeclineFriend(message, ws, wsId);
} else if (message.type === 'sendchatmessage') {
sendChatMessage(message, ws, wsId);
} else if (message.type === 'getchatmessages') {
getChatMessages(message, ws, wsId);
} else if (message.type === 'sendglobalmessage') {
sendGlobalMessage(message, ws, wsId);
} else if (message.type === 'getglobalmessages') {
getGlobalMessages(message, ws, wsId);
} else if (message.type === 'getconversations') {
handleConversations(message, ws, wsId);
} else if (message.type === 'geteventmessages') {
handleGetEventMessages(message, ws, wsId);
} else if (message.type === 'sendeventmessage') {
handleeventmessage(message, ws, wsId);
} else if (message.type === 'geteventlist') {
getEventList(message, ws, wsId);
} else if (message.type === 'geteventinfo') {
geteventinfo(message, ws, wsId);
} else if (message.type === 'fetchprofilephoto') {
fetchProfilePhoto(message, ws, wsId);
} else if (message.type === 'profile_picture_upload') {
const { username, image: encodedImage, message: textMessage } = message;
uploadProfilePicture(username, encodedImage, textMessage, ws);
} else {
console.log('Unknown message type:', message.type);
}
} catch (error) {
console.error('Error parsing message:', error);
}
});

// Handle WebSocket connection close
ws.on('close', () => {
console.log('WebSocket connection closed');
// Remove the closed connection from the object and userSocketMap
for (const id in connections) {
if (connections[id] === ws) {
delete connections[id];
const username = userSocketMap[id];
if (username) {
delete userSocketMap[id];
console.log(`Connection removed for user: ${username}`);
}
break;
}
}
});
});

const fetchProfilePhoto = async (message, ws) =>  {
try {
const { username } = message;
const profilePicturePath = path.join(__dirname, 'profilepictures', `${username}.jpeg`);

// Check if the profile picture exists
if (fs.existsSync(profilePicturePath)) {
// Read profile picture as base64
const base64Image = fs.readFileSync(profilePicturePath, { encoding: 'base64' });

// Send success message with base64 encoded image to the client
ws.send(JSON.stringify({
type: 'fetchprofilephotosuccess',
image: base64Image
}));
} else {
throw new Error('Profile photo not found for the user');
}
} catch (error) {
console.error('Error fetching profile photo from server:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Failed to fetch profile photo' }));
}
};

async function uploadProfilePicture(username, imageBase64, ws) {
// Remove the data header from the Base64 string if it exists
const base64Data = imageBase64.replace(/^data:image\/jpeg;base64,/, "");

// Create a buffer from the Base64 data
const imageBuffer = Buffer.from(base64Data, 'base64');

// Define the directory where you want to save the profile pictures
const profilePicturesDir = path.join(__dirname, 'profilepictures');

// If the directory does not exist, create it (you may remove this if directory exists always)
if (!fs.existsSync(profilePicturesDir)) {
fs.mkdirSync(profilePicturesDir);
}

// Define the file path for the new profile picture
const filePath = path.join(profilePicturesDir, `${username}.jpeg`);

// Write the file to the defined path
fs.writeFileSync(filePath, imageBuffer);

}

async function registerWSID(message, ws, wsId) {
try {
const { username, authToken } = message;

// Verify auth token and token expiry against Users table
const connection = await connectToDatabase();
const query = 'SELECT authToken, TokenExpiry FROM Users WHERE username = ?';
const results = await executeQuery(connection, query, [username]);

if (results.length === 1) {
const user = results[0];
const currentDate = new Date();
const tokenExpiryDate = new Date(user.TokenExpiry);

if (user.authToken === authToken && tokenExpiryDate > currentDate) {
// Update userSocketMap with wsId and username
userSocketMap[wsId] = username;

console.log(`${username} successfully registered WSID`);
ws.send(JSON.stringify({ type: 'registerwsid_success', message: 'WSID registered successfully' }));
} else {
// Token is invalid or expired
console.log(`Authentication failed for ${username}`);
ws.send(JSON.stringify({ type: 'Auth_Failed', message: 'Authentication failed' }));
ws.close();
}
} else {
// User not found or multiple users found
console.log(`Authentication failed for ${username}`);
ws.send(JSON.stringify({ type: 'Auth_Failed', message: 'Authentication failed' }));
ws.close();
}

connection.end();
} catch (error) {
console.error('Error registering WSID:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Failed to register WSID' }));
}
}

Я даже добавил функцию RegisterWSID, поэтому, когда MainActivity запускается после входа в систему и возобновления работы, вы сразу же регистрируетесь в веб-сокете в качестве клиента по имени пользователя из общих настроек.
Я пытался использоватьchatgpt, чтобы узнать, не упустил ли я что-то, я пытался скопировать и изменить получателя уведомлений с sendchatmessage, но ничего, я просто получаю сообщение «не найдено соединение с веб-сокетом для xxx» в журнале консоли ssh. p>
Мое единственное другое решение — установить задержку сообщения на стороне клиента, которая извлекает все новые запросы друзей и списки сообщений, но это не совсем то, что мне нужно.

Подробнее здесь: https://stackoverflow.com/questions/787 ... s-accepted
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Можно ли отследить отправителя, если запрос отправителя относится к приложению, которое еще не установлено?
    Гость » » в форуме IOS
    0 Ответы
    39 Просмотры
    Последнее сообщение Гость
  • Сокет равен нулю. Пожалуйста, проверьте, правильно ли принят вызов [закрыто]
    Anonymous » » в форуме C#
    0 Ответы
    35 Просмотры
    Последнее сообщение Anonymous
  • Веб-сокет сервера в js и клиентский веб-сокет в Java Android
    Anonymous » » в форуме JAVA
    0 Ответы
    27 Просмотры
    Последнее сообщение Anonymous
  • Как я могу сделать запрос на добавление в друзья в Roblox?
    Anonymous » » в форуме Python
    0 Ответы
    13 Просмотры
    Последнее сообщение Anonymous
  • Как я могу сделать запрос на добавление в друзья в Roblox?
    Anonymous » » в форуме Python
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Android»