how to disconnect socket on session expire - javascript

I have a small express application this also contains the socket program. When ever user success login it creates the session and socket connection perfectly.
But MY problem was when the express session expire or session delete by cookie manager, the socket still in the active connection. it receiving the messages. how to disconnect even if the session are not available after the success login.
Here my code was:
This is my html file which gets the alert message:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="socket.io.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
contentType: 'application/json',
url: './alert'
});
});
</script>
<script>
var socket = io.connect();
socket.on('message',function(data){
alert(data.msg);
});
</script>
</head>
<body>
<button>alert</button>
</bodY>
</html>
This is my socket and express code:
var express=require('express');
var app=express();
var session = require('express-session');
var server=require('http').createServer(app);
app.use(session({secret: 'abcd',resave:'false', saveUninitialized:'false',name:'usess',cookie: { maxAge: 10000 }));
var io=require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.join('alerts');
socket.on('disconnect',function(data){
socket.leave('alerts');
console.log('leaved');
});
});
app.get('/login', function(req, res){
//here my authentication code//
req.session.login='logedin';
req.session.save();
res.sendfile('./template.html');
});
app.get('/', auth,function(req, res){
//index file contins the two text boxes for user name and pass//
res.sendfile('./index.html');
});
app.get('/alert',function(req,res){
io.sockets.in('alerts').emit('message',{msg:'hai'});
res.end();
});
server.listen(3000);
Thank You.

Maybe you can check if the req.session exists before emitting the message ?
app.get('/alert',function(req,res){
if(req.session)
io.sockets.in('sairam').emit('message',{msg:'hai'});
else
//Disconnect the client from server side
res.end();
});
For disconnecting the socket from server side check this answer;
https://stackoverflow.com/a/5560187/3928819

Related

Catch "signal" in routing page

I have create a socket in app.js
APP.JS
var app = express();
var server = require('http').createServer(app)
var io = require('socket.io').listen(server);
app.set('socketio', io);
io.sockets.on('connection', function(socket){
console.log('Connesso');
socket.on('message', function(data){
console.log("Oo");
})
})
In my html page I have a js script
newex.onsubmit = function(event){
event.preventDefault();
socket.emit('message', {
name: document.getElementById('name').value,
desc: document.getElementById('description').value
});
}
So, when an user submit a form, the socket should send a "signal", but I want catch the signal in a routing page, not in my app.js
I tried with:
ROUTING PAGE
io = req.app.get('socketio');
io.on('message', function(message){
console.log(message);
})
But it doesn't work! I get that I need to put io.on(...) into io.sockets.on clousure but I don't get why. Can you explain me mechanism of socket.io?
EDIT
I set 'socket' in this way and I try code of tbking but it doesn't work anyway
io.sockets.on('connection', function(socket){
console.log('Connesso');
app.set('socket', socket);
//socket.on('message', function(message){console.log("Ricevuto")})
})
You need to listen to the messages from the specific socket the client is connected to.
Try this in your routing file:
var socket = req._socket;
socket.on('message', function(message){
console.log(message);
})

How do I properly emit data to server from client using Node.js?

When the client connects to the server a message is supposed to be emitted to the console. I'm not getting any errors so I'm confused as to what my problem actually is.
Server: As you can see the client connects.
Client: The message doesn't appear in the console.
(Forgive me for the links, I don't have 10 reputation)
How do I get the message to print to the console?
I've read other posts like this one, but they weren't helpful :(
When you do io.connect(), that call is asynchronous and not immediate. You cannot immediately emit to the server until the client generates the connect event:
var socket = io.connect()
socket.on('connect', function() {
// it is safe to call `.emit()` here
socket.emit("sndMsg", someData);
});
index.html
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
server.js
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
});
app.listen(3000);

Why does my Angular POST request for PHP file return 404?

I posted the code for my index.html, app.js and insert.php.
The dependencies installed are express, mysql and morgan.
In my folder I have
/node_modules
app.js
index.html
insert.php
package.json
I have a WAMP local server running in the background. phpMyadmin's username is root and password is blank, by default. I've set up a database called storestuff with a table in it named thestuff which has two columns title and content.
So I run node app.js in the terminal and then get
Server running on port 3000.
Connected successfully to the database.
Now, I go to visit localhost:3000
When the page loads, terminal shows GET / 304 20.635 ms - - which means the page loaded correctly.
I've also inserted some dummy data into the MySQL storestuff database using phpMyAdmin for testing purposes. Visiting localhost:3000/load which is a route set up in app.js, terminal shows GET /load 200 16.382 ms - -
which shows in the browser, a page with JSON data which is indeed the dummy data I had inserted and http code 200 means the GET request worked properly.
When I fill out the title field and the content field and press submit, terminal shows POST /insert.php 404 2.949 ms - 150 which I don't understand because insert.php is in the same folder as index.html.
index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro">
</head>
<body>
<font face="Source Sans Pro">
<div ng-app="myApp" ng-controller="myController">
<h1> Hello world! </h1>
<form>
Title <input type="text" ng-model="title"><br>
Content <input type="text" ng-model="content"><br>
<input type="button" value="Submit" ng-click="insertdata()">
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function($scope, $http) {
$scope.insertdata = function() {
$http.post('insert.php', {
'title':$scope.title,
'content':$scope.content
})
.then(function(data) {
console.log("Data inserted into the MySQL database successfully.");
});
}
});
</script>
</div>
</font>
</body>
</html>
app.js
var express = require('express');
var mysql = require('mysql');
var morgan = require('morgan');
var app = express();
app.use(morgan('dev'));
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'storestuff'
});
connection.connect(function(error) {
if(error) console.log("Problem connecting to MySQL: " + error);
else console.log("Connected successfully to the database");
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/load', function(req, res) {
connection.query("SELECT * from thestuff", function(err, rows) {
if(err) console.log("SELECT from thestuff... did not work: " + err);
else res.end(JSON.stringify(rows));
});
});
app.listen(3000, function() {
console.log("Server running on port 3000.");
});
insert.php
<?php
$data = json.decode(file_get_content('php://input'));
$title = mysql_real_escape_string($data->title);
$content = mysql_real_escape_string($data->content);
mysql_connect('localhost', 'root', '');
mysql_select_db('storestuff');
mysql_query("INSERT INTO thestuff('title', 'content') VALUES('".$title"', '".$content"')");
?>
add this in the top of your php file
<?php
header("Access-Control-Allow-Origin: *");
try with headers property
$http({
method: 'POST',
url: 'insert.php',
data: {'whetever':'data', 'in':'json format'},
headers: {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.then(function(res){
console.log('successful response', res);
.catch(function(err) {
console.error('Error while post', err);
});
and you can access in on insert.php
header("Access-Control-Allow-Origin: *");
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)) {
$_POST = json_decode(file_get_contents('php://input'), true);
echo $data->whatever;
}
Note: you can also you set it globally for all post request within .config block as below
myApp.config(function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
You are using node to power your web server. Couple of things: in your app routes you don't have a route for app.post ('/insert.php'), which is the cause of your 404. But node.js itself won't interpret php files for you, so at best it will show the code for the php file. There are plugins you can use or use another web server like nginx in front of the express/nodejs.

Socket.io > Simple server to client message

my problem between socket.io and HTML5
Javascript Server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendfile('index.html');
});
io.on('connection', function (socket) {
socket.emit('news', 'Hello');
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
HTML5:
<html>
<head>
<meta charset="UTF-8">
<title>My Title</title>
</head>
<body>
<input type="button" id="getButton" value="Get Rooms">
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$("#getButton").click(function () {
socket.on('news', function (data) {
alert(data);
});
});
</script>
</body>
</html>
When I click on the button (ID: getButton) I don't get an alert. The server ist working and I can access the page without any problems.
I am currently a newbie in socket.io/javascript (installed yesterday), if you have good informative pages about socket.io please post the link under this topic, thanks.
best regards
You're emitting the news message as soon as you connect, so it has already fired by the time you click your button. Try changing your code to this and you should see your alert:
var socket = io();
socket.on('news', function(data) {
alert(data);
});
You could trigger the event on a button with something like this:
Server:
io.on('connection', function(socket) {
//socket.emit('news','Hello');
});
// Return the news when it's requested
io.on('giveMeNews', function(socket) {
socket.emit('news', 'Here is your news');
});
Client:
// Listen for the news message
socket.on('news', function(data) {
alert(data);
});
// Request news from the server
$("#getButton").click(function() {
socket.emit('giveMeNews');
)};

Client is not receiving message from server in socket.io

My server wants to send to the clients a message on connection. Then the client sends a message to the server .
My code is working fine when the client sends message to the server but the initial message that the server should send on connection is not received by the client.
This is my little code :)
server
var app = require('http').createServer(handler),
io = require('socket.io').listen(app, { log: false }),
fs = require('fs');
app.listen(8001);
function handler(req, res) {
fs.readFile(__dirname + '/client1.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client1.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log("running time");
socket.emit("serverMessage","server says hi");
socket.on('clientMessage', function () {
console.log("client message recieved");
});
});
client
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
socket = io.connect("http://localhost:8001");
socket.on('connection', function(socket) {
socket.on("serverMessage", function(d) {
console.log("server send a message ");
});
});
function send() {
socket.emit('clientMessage', "Test Message From Client");
}
</script>
</head>
<body>
<button onclick="send()" >send</button>
</body>
Please any help?
There is a simple error in your client code. There is no event named connection for client. Instead the name is connect. Do this in client:
<script>
socket = io.connect("http://localhost:8001");
</script>
<script>
socket.on('connect', function(socket) {
socket.on("serverMessage", function(d) {
// you can alert something here like alert(d)
console.log("server send a message ");
});
});
</script>

Categories

Resources