I am new in socket development. I am creating chat using socket io, frontend is ios and backend is node js. I want to send message notification for disconnected users. Like we get notification if whatsapp is not opened. How can I do that ?
You can catch the person's exit with Socket.io and send a notification with push.js
socket.on('disconnect', function () {
console.log('user disconnected');
Push.create(data.user_name + " | Chat", {
body: data.desc,
icon: "https://pushjs.org/images/icon.png",
tag: "chat",
link: "http://localhost:8080/chat",
timeout: 5000,
onClick: function () {
window.focus();
this.close();
}
});
});
Related
socket.on('new-notification', function(data) {
let room_id = data.room_id;
var receiver_id = data.receiver_id;
var booking_request_id = data.booking_request_id;
var message = {
to: notification_payload,
collapse_key: 'green',
notification: {
title: 'Tittle',
body: "New message from User",
icon: site_url + 'assets/icons/icon- 72x72.png',
sound: 'default',
url: redirect_url,
},
data: {
title: 'Tittle',
body: "New message from User",
icon: site_url + 'assets/icons/icon- 72x72.png',
sound: 'default',
url: redirect_url,
}
};
fcm.send(message, function(err, response) {
if (err) {
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});
}
});
}
else {
}
}
});
});
I have an Angular PWA that is using Socket.io Node and express server for real time messaging and push notifications using Firebase Cloud Messaging. Messaging works fine but the problem is that when ever the user goes out of the app they won't be able to receive notifications but only receive when actively on the app. My assumption is that Socket io is disconnecting when the user leaves the app. So is there any way to make sure that socket remains active even if the app is running in the background.
i have attached my notification snippet. Your help will be greatly appreciated
To do this, you will need to set up a service worker for Angular, these run and keep your app alive to do certain tasks when the device would normally put apps into sleep mode.
you can follow the latest Angular documentation on creating service workers HERE
In my MERN app I have the following code:
Server:
io.on('connection', (socket) => {
socket.join('main');
socket.on('start session', function(data){
socket.join('sockets');
});
socket.on('try', () => {
io.in('main').emit('test', 'hi');
io.in('sockets').emit('test', 'hello');
console.dir(socket.rooms);
})
});
Client:
componentDidMount() {
socket.on('connect', function(){console.log('connected to socket')});
socket.on('test', function(data){console.log(data)});
socket.on('event', function(data){console.log(data)});
socket.on('error', (error) => {
console.log(error)
});
}
setSession(id, slug) {
if(!this.state.sessionId) {
socket = io(serverUrl);
this.setState({ sessionId: id, slug: slug });
let sessionInfo = {room: id, slug: slug};
console.log(`Session local init. SessionId: ${id}, Slug: ${slug}`);
socket.emit('start session', sessionInfo);
}
}
In a separate client component I emit the 'try' event when I click a button.
The server console validates that the socket is in both rooms (this is called after we emit the events, so there is no way the socket's rooms are being changed/overwritten)...
{
ub1_9Nw3sMtfZQtBAAAF: 'ub1_9Nw3sMtfZQtBAAAF',
main: 'main',
sockets: 'sockets'
}
...however, the client only receives the event emitted to the 'main' room, and not the 'sockets' room. The server thinks the client is in both rooms and the only difference is that the 'sockets' room assignment is in an event callback and the 'main' room assignment is at the top-level of the 'connection' function. Thoughts?
For now, I've managed to bypass this issue by sending the room name in the query param when the client connects.
Client:
socket = io(serverUrl, {query: {id: id}});
Server:
io.on('connection', (socket) => {
socket.join(socket.request._query.id);
socket.on('try', (data) => {
io.to(data).emit('join', 'bang');
})
});
...however it still seems as if the original code should have worked - very little else has been modified. Leaving the question up because a workaround isn't a solution and this isn't best practice!
You only join the 'sockets' room if the client emits a 'start session' event.
socket.on('start session', function(data){
socket.join('sockets');
});
Client only seems to be emitting 'start session' in setSession, and I don't see that method getting called anywhere.
I have a react native 0.59 app with nodejs 10.2 as backend. The socket.io 2.2.0 running on a server and it is 2.1.1 running on the app client. Here is the socket related code:
Nodejs server:
All socket.io related code is in the index.js file:
io.on('connection', (socket) => {
console.log("socket.id : ", socket.id);
socket.on('message', (msg) => {
console.log("msg received by server socket : ", msg);
});
console.log("Socketio server is initialized");
//disconnect
socket.on('disconnect', async function() {
try {
await SocketList.update({
active: false
}, {
where: {socket_id: isocket.id}
});
} catch(err) {
console.log("err in false socket id", socket.id);
}
console.log('disconnected event');
});
});
A listener for message is implemented.
React Native App:
The socket.io client used is 2.1.1. The socket is initiated in App.js and pass to Chat component. In the Chat component, connect is made with the socket to the server and emit a message:
App.js:
//socket.io
const socket = io(GLOBAL.BASE_URL, {
transports: ['websocket'],
jsonp: false
});
let props = {
eventId: "",
user: ""
};
const ChatWithSocket = (props) => (<Chat {...props} socket={socket} />)
//create the navigator
const navigator = createStackNavigator(
{
Event: Event,
Chat: {
screen: ChatWithSocket,
}
}, {
initialRouteName: "Event"
}
);
Component Chat.js:
When user enter a chat message and click send, The socket fires up the connect and emit a message with the message entered by the user:
_onSend(messages = []) {
console.log("socket.io in chat _onSend : ", this.props.socket.id);
this.props.socket.connect();
this.props.socket.on('connect', () => {
socket.emit("message", {msg: messages[0].text});
});
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
The problem is after the chat message is sent from the app, there is no response from the server and the following socket listener code is not executed:
socket.on('message', (msg) => {
console.log("msg received by server socket : ", msg);
});
Here is the console output (portion) on Nodejs server:
Listening on port 3000...
Executing (default): SELECT 1+1 AS result
DB connection has been established successfully.
socket.id : U0Vm-O5ainh-IRusAAAA
Socketio server is initialized
err in false socket id U0Vm-O5ainh-IRusAAAA
disconnected event
socket.id : 7qo9ncTog0dhPfL6AAAB
Socketio server is initialized
The initial socket connection was closed and the socket 7qo9ncTog0dhPfL6AAAB is initiated again.
Here is the app console output showing 2 messages have been sent by client 7qo9ncTog0dhPfL6AAAB which matches the socket.id on the server:
4-14 22:21:19.034 26574 26634 I ReactNativeJS: 'socket.io in chat _onSend : ', '7qo9ncTog0dhPfL6AAAB'
04-14 22:21:24.286 26574 26634 I ReactNativeJS: 'socket.io in chat _onSend : ', '7qo9ncTog0dhPfL6AAAB'
I'm starting to work with Socket.io and my nodeJS API
I succeeded to get my user connected, and showed a message on my server.
But now, I'm trying to send data to my client -> then server -> then client again etc.
But when I use emit nothing appends... So this i my code :
SERVER SIDE
io.on('connection', function(socket){
console.log("user connected") // I see that
socket.emit('text', 'it works!'); //
socket.on('test1', function (data) {
console.log('received 1 : '); // Never showed
console.log(data); // Never showed
});
}
CLIENT SIDE
var socket = io.connect(myUrl); // good connection
socket.emit ('test1', {map: 4, coords: '0.0'}); // never showed on the server side
socket.on('text', function(text) {
alert(text); // never showed
socket.emit('test', { "test": "test2" });
});
Any ideas?
thanks !
Your Starter Code seems to be valid, you need to check two things :
if you successfully included the socket.min.js in the client side
if you re having any error printed in the console
On the client side, you have to wait until the connection succeeds before it is safe to send data to the server. Connecting to the server is not synchronous or instantaneous (thus it is not ready immediately). You are trying to send data before the connection is ready.
Put your first send of data inside a socket.on('connect', ...) handler.
var socket = io.connect(myUrl); // good connection
// send some data as soon as we are connected
socket.on('connect', function() {
socket.emit ('test1', {map: 4, coords: '0.0'});
});
socket.on('text', function(text) {
alert(text); // never showed
socket.emit('test', { "test": "test2" });
});
this worked for me
CLIENT SIDE
//sending custom data to server after successful connection
socket.on('connect', function(){
this.socket.emit('client-to-server', {map: 4, coords: '0.0'});
});
//listening the event fired by the socket server
socket.on('server-to-client', function(dataSendbyTheServer){
// do whatever you want
console.log(dataSendbyTheServer);
});
SERVER SIDE
io.on('connection', function(socket) {
// listening the event fired by the client
socket.on('client-to-server', function (data) {
console.log('received 1 : ');
// sending back to client
io.emit('server-to-client', data)
});
});
Is there a way to set up socket.io listeners for certain clients after they execute a command? For example:
socket.on('setupServer', function (data) {
console.log("setupServer called");
// Now set up listeners
socket.on('serverAction', function (data) {
console.log('Listener for clients calling setupServer');
});
});
In the above, a client has connected and has issued a 'setupServer' command to the node.js server. The server now listens for 'serverAction' from the specific client. Other clients won't be able to use 'serverAction' without calling 'setupServer' first.
You could create a room and validate some data from user and then join those users to that room, after that emit some events to that users in that room.
Something like this.
server.js
var io = require('socket.io')(server);
io.on('connection',function(socket){
socket.emit('auth_user')
socket.on('response_from_user',function(data){
if(data.name === "Blashadow"){
//join that user to the room
socket.join('/room',function(){
//emit some custom event to users in that room
io.in('/room').emit('custom_event_room', { info: 'new used connected from room' });
});
}
});
});
client.html
var socket = io('localhost');
socket.on('auth_user', function (data) {
socket.emit('response_from_user', { name : "Blashadow" });
});
socket.on('custom_event_room',function(data){
console.log(data);
});