Use the same socket.io connection in multiple HTML pages in node js - node.js

-Follwing is the jquery code I have written in my (dashboard.html) file
<script>
$(function(){
$("#username").hide();
var socket= io.connect();
$(document).on("click", ".help", function () {
alert( $(this).attr('id'));
socket.emit('help',{helper:$username.val(),requester:$(this).attr('id')});
});
});
---On clicking help button socket will emit an event "help" as you can see in the code.
---Following is the app.js file on server
io.sockets.on('connection',function(socket){
socket.on('help',function(data){
console.log('rohi is goood',data.helper);
socket.emit('loadList' , {helper:data.helper,requester:data.requester});
});
});
---On "help" event socket is emitting an event "loadList" in app.js file.
Now I want to use "loadList" event in some other html file like "chat.html".
The code I have written is as follows for chat.html.
<script>
$(function(){
// var socket= io.connect();
// var socket= io.connect('http://localhost:3000/', { 'force new //connection': true });
socket.on('loadList',function(data){
alert('inside help',$('#usernam').val());
console.log('tatai',$('#usernam').val());
if($('#usernam').val()== data.helper){
$('#chatList').append('<p>'+data.requester+'</p>'+'<button value="chat"></button>');
}
else if($('#usernam').val() == data.requester){
$('#chatList').append('<p>'+data.helper+'</p>'+'<button value="chat"></button>');
}
else {
alert('fuck off');
}
});
The above code is not working. Please tell me how can I use same socket connection in the chat.html file.(loadList event is not working).

As your question is not complete so i am assuming you want to know if socket.io connection can be used on different html pages . Yes you can access it on every html page of your application as long as you have one server on which socket.io is used .
Every time a new user comes a socket session is created for that particular user and that user can access any page of your application .

Related

Keep connected users through website pages using nodejs

I have admin page with active users list. It works but when "userX" change to another page all clients are updated having no "userX" in active users list. Before 1 secound "userX" returns to active users list.
SERVER CONSOLE
UserX connected...
UserX disconnected... (UserX change to another page inside application)
Reason: transport close
UserX connected... (Because main layout force connection)
When "userX" change to another page nodejs fires socket.on('disconnect',function(){}) action.
This causes Client disconnected... (UserX change to another page inside application)
Reason: transport close
SERVER CODE
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(81, function () {
console.log('NodeJs listening on port:81');
});
io.on('connection', function (socket) {
console.log('New client connected...');
socket.on('disconnect', function (reason) {
console.log('Client disconnected...');
console.log('Reason: ' + reason);
});
});
PAGE CODE
<script type="text/javascript">
var socket = io(':81', {forceNew: true});
</script>
How to keep user connected between pages and fire disconnect only when browser get closed or user get logging out?
If you are using page redirect for change the page then page will be refreshed.And every time when page got refreshed the socket will disconnect.
For that, you have to use internal routing to load another page.
Check this answer
Ajax load page without refresh

how to display a realtime variable in nodejs in HTML

I am using the setInterval() function to update a few variables(prices from various API's) every 'x' seconds in NodeJS
I want to display these variables in HTML and have them update real time every 'x' seconds.
How do I go about this using Socket.io or without using it
If you don't want to use socket.io, you can use AJAX calls but I think it's the more painful way...
If you use socket.io, there are great examples on their GitHub : Chat example.
In your NodeJS :
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', incremental);
socket.emit('update-value', incremental); // Emit on the opened socket.
incremental++;
}, 1000);
});
This code should be start in your application.
And in your view :
<html>
<body>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
My code isn't complete but shows the essential to know.
Try Templating and template engines.
Template engine are stuff that enable you to pass variables to Templates. These engines render the template file, with data you provide in form of HTML page.
I will suggest you to try 'ejs', as it very closely signify HTML files. ejs template are simply HTML syntax with placefolder for you to pass Data.
But that will require you to refresh the page continously after regular time. So you can try 'AJAX' which let you refresh part of page, simultaneously sends and receives data from server

Chat App using Socket.io and Node.js

I am developing chat app using Node.js and Socket.io.
Here is my code.|
socket.js
var io = require('socket.io').listen(8001);
var http = require('http');
var url = require('url');
var fs = require('fs');
// open the socket connection
io.sockets.on('connection', function (socket) {
// listen for the chat even. and will recieve
// data from the sender.
socket.on('chat', function (data) {
// default value of the name of the sender.
var sender = 'unregistered';
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat Message By: ', name);
console.log('error ', err);
sender = name;
});
// broadcast data recieved from the sender
// to others who are connected, but not
// from the original sender.
socket.broadcast.emit('chat', {
msg : data,
msgr : sender
});
});
// listen for user registrations
// then set the socket nickname to
socket.on('register', function (name) {
// make a nickname paramater for this socket
// and then set its value to the name recieved
// from the register even above. and then run
// the function that follows inside it.
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "Hello " + name + '!',
msgr : "Mr.Server"
});
});
});
});
index.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var name = '';
var socket = io.connect('http://localhost:8001');
// at document read (runs only ones).
$(document).ready(function(){
// on click of the button (jquery thing)
// the things inside this clause happen only when
// the button is clicked.
$("button").click(function(){
// just some simple logging
$("p#log").html('Sent message: ' + $("input#msg").val());
// send message on inputbox to server
socket.emit('chat', $("input#msg").val() );
$("p#data_recieved").append("<br />\r\n" + name + ': ' + $("input#msg").val());
// then we empty the text on the input box.
$("input#msg").val('');
});
$("#btnSubmit").click(function(){
alert("Disconnected");
//socket.clients[kickedUserSocketId].onDisconnect();
socket.close();
});
// ask for the name of the user, ask again if no name.
while (name == '') {
name = prompt("What's your name?","");
}
// send the name to the server, and the server's
// register wait will recieve this.
socket.emit('register', name );
});
// listen for chat event and recieve data
socket.on('chat', function (data) {
// print data (jquery thing)
$("p#data_recieved").append("<br />\r\n" + data.msgr + ': ' + data.msg);
// we log this event for fun :D
$("p#log").html('got message: ' + data.msg);
});
socket.emit('forceDisconnect');
</script>
</head>
<body>
<input type="text" id="msg"></input>
<button>Click me</button>
<p id="log"></p>
<p id="data_recieved"></p>
</body>
<input id = "btnSubmit" type="submit" value="Disconnect"/>
</html>
I am running first socket.js from command prompt. After that, I am running .html file in browser 2 times. Now 2 users can chat via browsers. But when I am trying to put my .js file and .html file on server which I have created using FileZila and running .js file, it is running but when I am trying to run .html file on server side(In this case FileZila) , by giving the IP address and Port number of server it is not running. Can you tell me what is the problem?
This doesn't seem to be a nodejs-issue.
You have a server that should be reachable by IP with something like 'http://your.domain.or.ip:80'.
If you get a "can't connect" in your browser then make sure there is no firewall in its way and that port (in the example: 80) is reachable from your browser location (aka known as "your pc"). Please note that you have your socket-service on port 8001 and your web server maybe runs on a different port? Make sure both ports are open.
If you get a blank page, check the browser javascript error messages.
There is a chance that you forgot to upload the file 'socket.io.js' in that directory '/socket.io/'. Try to download that file directly to see if your server serves.

Accessing server side functions using Express.js and EJS

I'm running a test app in Express.js using EJS as the templating engine. I'd like to access functions stored in a .js file to run server side and not client side. For instance if I have:
<%= console.log("I'm in the server console"); %>
the server catches the console output, and if I have:
<script type="text/javascript"> console.log("I'm in the client-side console"); </script>
Now if I have a function to output the same for the client side I can include it this way:
<script type="text/javascript" src="/javascripts/clientSideCode.js"> clientSideOutput(); </script>
But how do I include a file and its functions that way so EJS can execute server side code? It appears that the public folder in express is just for client side code.
You can create helper functions that your templates can access via app.locals:
http://expressjs.com/api.html#app.locals
You can use node.js and Socket.IO to emit real time events between client and server. For instance the client would do something like:
<script>window onload = function() {
socket.emit('request_customer_list', { state: "tx" });
socket.on('receive_customer_list', function(data) {
$.each(data.customer_list, function(key, value) {
socket.set(key, value); // store the customer data and then print it later
});
});}
On your server you can have a routine to load the customer list and send it back in similar format:
socket.on('connection')
socket.on('request_customer_list', function(data){
state = data.state;
var customer_list;
// pretend i loaded a list of customers from whatever source right here
socket.emit('receive_customer_list', {customer_list: customer_list});
)} )};

socket.io get data from onclick action then pass the data to other pages to execute the data

I want to create a page using node.js and socket.io.
There are two buttons inside the page, when I click one of them, it will change a variable which defines the animation-duration(I omit the CSS animation codes here).
When I open the same page on another web-browser and click one of the buttons, I hope to see the change in both of the webpages. I don't know how to write the code inside the socket.on('chat', function(data){???}); to make two pages communicate with each other.
Client side:
//socket.io codes--
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://localhost:3000');
socket.on('chat', function (data)
{
function change_position(data)
{
document.getElementById("animation1").style.WebkitAnimationDuration=data;
}
});
</script>
.....
//action--
<body>
<button id="1b" type="button" style="position:absolute; left:377px; top:220px;" value="2s"; onclick="change_position(value)"> - 1 - </button>
<button id="2b" type="button" style="position:absolute; left:477px; top:220px;" value="15s"; onclick="change_position(value)"> - 2 - </button>
</body>
server side:
var io = require('socket.io'),
connect = require('connect');
var app = connect().use(connect.static('public')).listen(3000);
var chat_room = io.listen(app);
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
chat_room.sockets.emit('chat', data);
});
});
If your want a message to propagate to all clients/sockets, in your server you should have something like:
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
socket.broadcast.emit('chat', data);
socket.emit('chat',data);
});
});
The line socket.emit('chat',data); allows you to send the message back also to the sender of it, because broadcast will send it all other sockets.
Of course, you could ommit that line and handle the message sending logic in the client; i.e. adding some JavaScript code that makes the changes you want just after sending the message to the server.
You can emit on your client using socket.emit('message', data). Then on the server get it with chat_room.socket.on('message', data). Emit it to the clients using chat_room.sockets.emit('message', data).

Resources