I want to send message to specific socket . I have saved the socketId in mongoo db . when i emit the event its not emitting the event . its works fine if i emit without specific socket what could be the issue ./ please help me
here is my code
io.on('connection', function (socket) {
socket.on('save-message-private',function(data){
console.log('private messgae ')
OnlineUsers.find({username:data.receiver},function(err,res){
if(!err){
// console.log(res)
console.log(res[0].socketId)
io.to(res[0].socketId).emit('new-message-private', { message: res });
}
else
console.log(err)
})
})
});
And here is my front end in angular 4
ngOnInit() {
var user = JSON.parse(localStorage.getItem("user"));
console.log(user)
if(user!==null) {
this.socket=io('http://localhost:4000',{query:"username="+user.nickname});
this.getChatByRoom(user.room);
this.msgData = { room: user.room, nickname: user.nickname, message: '',receiver:'group' }
this.joinned = true;
this.scrollToBottom();
this.getOnlineUsers();
this.socket.on('new-message', function (data) {
if(data.message.room === JSON.parse(localStorage.getItem("user")).room) {
this.chats.push(data.message);
this.msgData = { room: user.room, nickname: user.nickname, message: '' }
this.scrollToBottom();
}
}.bind(this));
this.socket.on('new-message-private',function(data){
console.log('private new')
console.log(data);
}.bind(this));
}
}
new-private-message not working
My socketId saved in db was different from client side socketId . so I updated the socketId on db and problem solved
Related
I am trying to write an integration test for socket io. I am using try-catch for server event when the error is catched I emit an event for the client to handle the error
io.of('/rooms').on('connection', socket => {
const socketId = socket.id;
console.log('server socketid', socketId);
const userRepository = getCustomRepository(UserRepository);
const conversationToUserRepository = getCustomRepository(ConversationToUserRepository);
socket.on('initGroupChat', async (users_id, fn) => {
try {
const [user, listConversationToUser] = await Promise.all([
userRepository.findOne({
where: {
users_id,
},
}),
conversationToUserRepository.find({
where: {
users_id,
},
}),
]);
if (!user) {
throw new NotFoundError('User not found with id: ' + users_id);
}
console.log(2);
user.socket_id = socket.id;
await userRepository.save(user);
for (const item of listConversationToUser) {
socket.join(item.conversation_id.toString());
}
fn('init group chat success');
} catch (error) {
io.to(socketId).emit('error', errorHandlerForSocket(error));
console.log(10);
}
});
});
but on the socket client, nothing happens. here is the code socket client:
it.only('Init Group Chat with error', done => {
socket = io.connect(`http://localhost:${env.app.port}/rooms`, {
transports: ['websocket']
});
const id = 11111;
socket.emit('initGroupChat', id, (response: any) => {
console.log('response', response);
});
socket.on('error', (error: any) => {
console.log('error3', error);
done();
});
});
on the error event, the console.log did not show on the terminate. it didn't catch the event I emit on the server.
can anyone help me fix this issue
Every time the client Refresh socketId changes.
Server :
io.emit("send_to_client", {
userId: 112233,
data: "Hello user 112233"
});
Client :
var userLogin = 112233;
socket.on("send_to_client", function(res) {
if(res.userId === userLogin)
//somethingElse
});
I have a Vue app that sets up a socket connection when the user logs in.
My component has a method that accesses an outer variable socket I made so that I can emit events in other methods..
onLoginSuccess() {
socket = io(`${process.env.SERVER_URL}`);
socket.emit('login', localStorage.getItem('username'));
socket.on('login-response', (response) => {
if (!response.status) {
alert(response.message);
return false;
} else {
this.$router.push("/home");
this.$refs.form.reset();
}
});
}
However, when I try to do socket.emit in another event it doesn't work:
onSocketLogout() {
console.log('socket logout call', socket)
socket.emit('delete_username_from_array', localStorage.getItem('username') );
},
Socket doesn't seem to be null/undefined on the console and I tried putting the same event emitter on the onLoginSuccess function and it works fine. It just doesn't work when I use socket in other functions or places outside the initial connection.
Here's my socket io server code:
let logged_in_users = [];
const io = require('socket.io')(http);
io.on('connection', function(socket){
console.log(`Socket ${socket.id} connected`);
socket.on('login', function(username){
// check duplicates
if(logged_in_users.includes(username)){
socket.emit('login-response', {
message: 'It seems that you have already logged in on another browser. Please logout first.',
status: false
});
return false;
}else{
socket.emit('login-response', {status: true});
console.log(`${username} logged in`)
logged_in_users.push({ username, id: socket.id });
}
});
// for logout
socket.on('delete_username_from_array', function(username){
console.log('removing username from array')
// delete the username from the array of logged in users
logged_in_users.splice( logged_in_users.indexOf(username), 1 );
});
socket.on('test', () => {
console.log("TEST")
})
socket.on('disconnect', () => {
console.log(`Socket ${socket.id} disconnected`);
console.log(logged_in_users)
})
});
I established a chat between client and server.everything is fine but chat page needs to refresh to show recent messages.I tested using two different logins but the page which i refreshed is working fine but the other one not updating with recent messages
Server.js
io.on('connection', (socket) => {
console.log("---- client connected ----");
// send messages on every event
sendStatus = function (data) {
socket.emit('messages', data);
}
// get messages from the server
socket.on('send_message', function (data) {
new Chat({
user_id: data.user_id,
message: data.message,
date: data.date,
}).save(function(err, chat_data){
if (!err) {
Chat.findOne({ _id: chat_data._id }).populate('user_id').exec(function (err, chat) {
sendStatus(chat);
})
}
});
})
// send messages on load
Chat.find({}).populate('user_id').exec(function (err, chat) {
console.log('chattttttttt', chat)
socket.emit('onload_chat', chat);
})
})
Client.vue
mounted () {
this.getUsers()
this.$socket.on('messages', (data)=> {
this.chats.push(data)
console.log('on send message', data)
});
},
beforeMount () {
this.$socket.on('onload_chat', (data)=> {
this.chats = data
});
},
I'm new in node js and socket io, I'm trying to create interactive quizzes based on pin code given in the url for ex: http://domain/start/5555 should create a quiz page with name 5555 and when clients have the pin code they can connect to this quiz. So it means i have to have a quiz page which shows all connected clients for example but i have some prblems with io.sockets.in(pincode).emit()
because i don't know if i'm creating rooms correctly or not!
here is my code
Client.js
var socket = io();
socket.on('connect', function () {
var params = jQuery.deparam(window.location.search);// To get the name and the room
socket.emit('join', params, function (err) {
if (err) {
alert(err);
window.location.href = '/join.html';
} else {
console.log('No error');
}
});
});
Server.js
app.get('/start/:pincode', (req, res) => {
io.on('connection', (socket) => { // to rigester connection listener
console.log('New user is connected');
// When somebody connects it verifies if the name and the room are valid strings
socket.on('join', (params, callback) => {
if (!isRealSrting(params.name) || !isRealSrting(params.pincode)) {
return callback('Name and pincode are required');
}
socket.join(params.pincode);
users.removeUser(socket.id);//Remove the user from other places
users.addUser(socket.id, params.name, params.pincode);
var x = users.getUserList(params.pincode);
console.log(x);
io.sockets.in(params.pincode).emit('updateUserList', { //here it doesn't work i don't know why!
users: users.getUserList(params.pincode),
pincode: params.pincode
});
socket.emit('newMessage', {
user: params.name,
pincode: params.pincode,
readyMessage: 'You are connected'
});// when the user connect to the server he gets this message
callback();
});
socket.on('disconnect', () => {
var user = users.removeUser(socket.id);
if (user) {
io.emit('updateUserList', users.getUserList(user.pincode));
//io.to(user.room).emit('newMessage', generateMessage('Admin', `${user.name} has left`));
}
});
});
res.render('start.hbs', {
pincode: req.params.pincode
});
});
and the main page
Start.js
var socket = io();
var pincode;
socket.on('updateUserList', function (users) {
console.log('here');
var ol = jQuery('<ol></ol>');
var usercount = users.users.length; // Players number
pincode = users.pincode;
});
Any help or suggestion please?
I'm sending data to all clients but I need to send the data only one client (who make request) too.
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
......
});
}
There is a function called io.sockets.emit but there is no io.socket.emit.
I assume that in the post method you have identified the user or session.
So you can create a room per user to later emit on it.
client.js
var room = "#usernameRoom";
socket.on('connect', function() {
socket.emit('privateroom', room);
});
socket.on('privatemessage', function(data) {
console.log('Incoming private message:', data);
});
server.js
io.sockets.on('connection', function(socket) {
var socket_room;
socket.on('privateroom', function(room) {
socket_room = room;
socket.join(room);
});
socket.on('disconnect', function() {
if (socket_room) {
socket.leave(socket_room);
}
});
});
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
// now, it's easy to send a message to just the clients in a given private room
privateRoom = "#usernameRoom";
io.sockets.in(privateRoom ).emit('privatemessage', 'Never reveal your identity!');
});
}
hope that helps