private chat using socket.io in MEAN app - node.js

i am trying to include chat features on my MEAN app, all i have completed till now is a medium where all connected users can communicate.not a separate group. i follow some of the tutorials but they do by trick like sending some key words in front of message(whistle as they say).
as far as i know every connected users are provided a seperate socket ID through which communication is carried but i failed getting that id.
module.exports = function(socket){
//console.log(socket);
var users =[];
socket.on('username',function(data){
users.push({id:socket.id,username:data.message});
socket.emit('username',users)
})
console.log('connected');
socket.on('typing',function(data){
//socket.emit('typing',{message:"helo angular"});
socket.broadcast.emit('typing',{message:data.message});
});
It shows me socket is not defined, any one has better idea how to perform private message using socket.io and node.js
can anyone enlighten me about this.

Make all users join their own unique group.
socket.join(socket.id);
Then you can send a message to one user by doing this
io.sockets.in(whichever_user.id).emit('msg', "Hello there user lets have a private chat!");
I would recommend using the Express framework of Node, and implenting Socket.io into it.
Here are some links telling you how to set up Express and Socket.io:
https://www.youtube.com/watch?v=WH5qsGnFkBM&lc=z135dbryaqbfitiee22pd33ouozhwft3q
---Youtube comment tells you how to set up express generator.
Adrian GÄ…siewicz:
For those who want to have similar directory structure as Bucky:
Install Express generator "sudo npm install -g express-generator"
Go to directory where you want to create project and type "express myapp --ejs" 3. Select newly created directory --> "cd myapp"
Install all node_modules --> "npm install"
Run server --> "npm start"
Open browser and type "http://localhost:3000/" Have fun ;)
Using socket.io in Express 4 and express-generator's /bin/www
---This tells you how to set up socket in Node.js Express project.

Related

Call nodejs kafka script inside Angular 8 application

How to call nodejs kafka consumer script from Angular component.
I am able to run the same script in terminal using "npm filename.js" but it is throwing an error while calling same from Angular component.
An angular component runs on the client, the kafka script runs on the server. You'll have to create a proxy endpoint to call the script. Depending on which server side Web API Framework you're using this would be done different ways.
To help you understand this further, if you were using express.js, you'd need to have an endpoint to trigger the call (it should be a POST endpoint):
// POST method route
app.post('/triggerKafka', function (req, res) {
const exec = require('child_process').exec, child;
const testscript = exec('bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic yourTopic --from-beginning');
testscript.stdout.on('data', function(data){
console.log(data);
// sendBackInfo();
});
testscript.stderr.on('data', function(data){
console.log(data);
// triggerErrorStuff();
});
})
Now, I should say that this is probably not the way you want to do this. For one thing, you don't want to give people outside your control the ability to start and stop Kafka listening.
You should try to set up your Kafka consumer on the startup of your web application (server side); and provide a mechanism for connecting to it in a similar fashion as above -- proxying the calls through an API endpoint that you set up.
To start Kafka when your web application starts; you need to put the correct information in your node.js web application server startup. In your package.json if you have a "scripts" section you can add the following:
"scripts" : {
"start" : "<whateveryouhavenow>.sh && npm filename.js"
}
The important part here is the && npmfile.js; that says to run your command as well as the command that preceded it. There are more options here, but I provided just one.
Depending on what server side framework you're running and what task-running tool you're using, it would be different (whether it's npm, gulp, grunt, or something else).

Set up a server from within an electron app

I haven't had any success looking for this because I mostly find misleading questions, about people wanting to use data from a server inside of their electron app. That's not my case.
I have a regular app, which uses a server on the internet, just like any other, but we want to make it available for schools without internet (without any or without reliable internet), so what I'm trying to do is to create a version of my server which runs from an electron exe and serves files for the students conected to the wifi (but no the internet) to access. After the process is done "offline", I will sync the data from the electron app itself.
I tried to run a server from express but I didn't have any progress so far. What I tried was to put the exact same code from my node server in my main.js file and had no luck.
I know that's not what electron is supposed to do, if you're positively sure there is no way to do that, please tell me so I can search for another alternative.
A simple approach is to create a cluster where the master process is the Electron Main and the worker process is the server.
Example:
Change the main on package.json to start.js
On start.js write:
const cluster = require('cluster');
if (cluster.isMaster) {
require('./main.js'); // your electron main file
cluster.fork();
} else {
require('./server.js'); // your server code
}

call NodeJs method without load view

In my application NodeJs is running on xxx port. Mouse click event trigger node js function using socket.io. My application have real time notification feature.
My Question is
Can I trigger nodeJs method when real time notification comes from google
because, method which handle this notification not load any view ?
For pushing server to node you can use redis for that. you can use a code like below. so for that you need to install redis. you can find installtaion steps on google.
At your server side for e.g. you are getting the data into your function.
$redisobject = new Redis();
$redisobject->connect('127.0.0.1');
$purchase_info = json_encode(array('user_id' =>'2','purchase_information'=>'sample_data')); // json array of data which you want to post
$redisobject->publish('redis_data_php', $purchase_info); //your channel name and data.
Inside your node.js after installing redis module using npm
var redis = require('redis');
var redis_client = redis.createClient();
redis_client.subscribe('redis_data_php'); // same channel name as you have mentioned on php side
redis_client.on('message', function(channel, message){
var purchase_data = JSON.parse(message);
console.log(purchase_data);
socket.emit('redis_data', {"info" : purchase_data.purchase_information}); //emit your data to client as you want.
});
basically redis will create a channel between php and node.js so you can communicate via that channel.
Need to install below things
Install redis (if you are using ubuntu than follow this link https://www.digitalocean.com/community/tutorials/how-to-install-and-use-redis)
Than install redis for php (https://joshtronic.com/2014/05/12/how-to-install-phpredis-on-ubuntu-1404-lts/)
Install redis for node (npm install redis)
Hope this will work for you...

Troubleshooting socket.io error message

I inherited a project which utilizes node.js and socket.io, both of which I am not too familiar with.
I installed node.js and npm via homebrew and socket.io via npm.
The current setup has two different "sites": The frontend, that the user interacts with, and the backend that handles all the communications with a DB. The application uses several different displays, and the previous developer deemed it best to use the current setup.
I can successfully start the node server by invoking node node-server.js. In the head of the node-server.js, socket.io is being called like:
var sys = require('sys')
var exec = require('child_process').exec;
var io = require('socket.io').listen(8090);
[...]
In my front end, I call socket.io like this:
<script src="http://192.168.1.111:8090/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.1.111:8090');
[...]
However, when I debug the page, I get the following error messages:
SyntaxError: Unexpected identifier 'to' (anonymous function) socket.io.js:1
ReferenceError: Can't find variable: io sample.html
In the terminal window, where I started the node server, I get the output:
debug - served static content /socket.io.js
I should add that the two sites reside in separate folders - I access the frontend through a local Apache server, the piece that interacts with the DB sits someplace else on the same machine.
How would I correctly call the socket.io in my client?
Is there a way to enable better debugging?
Update
So the to in the error message, is because whenever the browser tries to load the socket.js file, it gets the reply of Welcome to socket.io

Error binding socket on heroku , not sure about using express

this is my first node.js and socket.io application , i didn't use express ,I want to deploy the application on heroku do i need to use it ? i mean i just did npm install socket.io on localhost and in my server file i.e game.js i have io = require("socket.io") and socket = io.listen(Number(process.env.PORT)) only and in one of the files where from where i am sending the message i have socket = io.connect();
so please tell me if i need to use express and how show i modify my existing application ?
I have given the link to the source of application
( https://github.com/bitgeeky/herokutest )
Although the Application works fine on localhost by changing the port no , to some port no like (8000) but Heroku error log on doing "heroku open" is http://pastebin.com/MtB0z5vQ
I noticed that you haven't created a http server. I am assuming that you are creating a web application, since you are deploying to heroku. For that, you need to create a http server in nodejs.
Go through socket.io https://github.com/LearnBoost/socket.io
Also http://socket.io/#how-to-use
This should get you started
Note: You do not need express. But it will make your work easier in many ways. Depends on the type of application that you want to create.

Resources