I'm making a private messaging app
PHP->MySQL
I store the messages in a mysql database, and whenever needed can be downloaded.
I'm new to socket.io and not sure how to do it correctly.
Let's say there are two users in the same chatRoom
userId | nickName | chatId |
---------|---------------|----------|
1 | "fred" | 1 |
2 | "john" | 1 |
ChatRooms:
chatId | chatName |
---------|---------------|
1 | "coolChat" |
// (and also I have a table for the chatMessages)
When user sends a message, the following happens:
The sendMessage.php:
$qry = $db->prepare('INSERT INTO chatMessages (chatId, userId, message) VALUES(:chatId, :userId, :message)');
$qry->bindParam(':chatId', $chatId, PDO::PARAM_INT);
$qry->bindParam(':userId', $userId, PDO::PARAM_INT);
$qry->bindParam(':message', $message, PDO::PARAM_STR);
$qry->execute();
if ($qry->rowCount() > 0) {
// let's say I collected all the users in the same chatRoom:
$chatRoomUsers = array(1, 2);
// Successfully inserted into the database, should somehow
// push the message with socket.io to another users in the same chatRoom
for($i=0; $i<count($chatRoomUsers); $i++){
// socket.push(toUserId: $chatRoomUsers[$i], inChatRoom: $chatId, message: $message);
}
}
The socket file so far:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var sockets = {};
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
var people = {};
socket.on('join', function(name){
people[socket.id] = name;
console.log(people);
});
So is there a way to send messages only to userId's in the same chatRoom?