xhr poll error come out is throwing while use socket.io - node.js

I wrote a very simple demo about socket.io And I package it by using phonegap. I found there is problem. After I open my app about ten seconds ,the connection will disconnect because of xhr poll error.if I refresh the page in disconnect event the error won't come again.
I use 1.2.0 version.here is my code. I already simplify it.
server:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
io.sockets.on('connection', function (socket) {
console.log("disconnect--"+socket.id+"--"+io.sockets.server.eio.clientsCount);
socket.on('disconnect', function () {
console.log("disconnect--"+io.sockets.server.eio.clientsCount);
});
});
http.listen(80, function () {
console.log("server statrt");
});
client:
$(document).ready(function () {
var socket = io("http://192.168.0.106:80");
socket.on('connect', function () {
alert("connect");
});
socket.on('error', function (data) {
alert(data);
});
socket.on('disconnect', function () {
alert("disconnect");
});
socket.on("reconnect", function () {
alert("reconnect");
})
});
thanks for help.my English is not very good

You have to open the socket.io connection when the deviceready event is fired.
document.addEventListener('deviceready', function() {
var socket = io("http://192.168.0.106:80");
socket.on('connect', function() {
alert("connect");
});
socket.on('error', function (data) {
alert(data);
});
socket.on('disconnect', function () {
alert("disconnect");
});
socket.on("reconnect", function () {
alert("reconnect");
});
});
Socket.io example

For those of you using Google Chrome, FYI Chrome does not fire 'deviceready'. Instead you should use 'DOMContentLoaded'.

Related

How to send message to frontend in case of MongoDb connection Failed

Is there any way to send error to frontend on mongoDb connection error.I had tried in a different different way but I didnt get a solution.
var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
app.get('/',function(req,res){
res.send('NOT Connected....')
});
});
You can use web sockets to push this information to the UI.
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('../..')(server);
const port = process.env.PORT || 3000;
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
socket.emit('mongodb-failed', error)
});
});
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
// when socket emits 'mongodb-connection-failed', this listens and executes
socket.on('mongodb-failed', (data) => {
// we tell the client to execute 'new message'
socket.broadcast.emit('mongodb-connection-failed', {
errorDetails: data
});
});
});
now at client side:
var socket = io();
socket.on('mongodb-connection-failed', () => {
console.log('you have been disconnected');
//do more whatever you want to.
});
This above example is using socket.io.
You can use any web socket library, see more here

NodeJS include functions

Lets say I have the following NodeJS file:
var https = require("https");
var express = require("express");
var app = express();
var options = {};
var serverPort = 8443;
var server = https.createServer(options, app);
var io = require('socket.io')(server);
var numUsers = 0;
app.get('/', function(req, res){
res.sendFile('/home/domain/index.php');
});
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
});
server.listen(serverPort, function(){
console.log("\n--------------------------------");
console.log('Node HTTPs Server');
console.log('Currently Listening on port %d',serverPort);
console.log("--------------------------------");
});
Since I can't get SNI to work on my server, I'll have to go the old fashioned way and write a script for each subdomain. But what I'd like to do is have the functions inside of the io.on('connection', function(socket) {} area to be included. So not included like a class or anything like that, but literally the code is just taken from another file and processed as if it were in that file already. A lot like PHP does includes. Is this possible?
Simplest solution would be to read code using fs.readFile[Sync] and pass it to eval inside io.on('connection', function(socket) {})
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
// eval function loaded outside io.on('connection')
eval(someFunctionBody);
// or
eval(fs.readFileSync('path/to/function/body.js'));
});
Can't you just use require?
functions.js
function myFunc() {
console.log("I am a funky func");
}
module.exports = {
myFunc,
myOtherFunc,
};
index.js
var https = require("https");
var express = require("express");
// snip
var funcs = require('./functions');
io.on('connection', function(socket){
// snip
funcs.myFunc();
});

I'm unable to connect to socket

I'm trying to connect to a socket.But I did not get the socketid on the console.Is it the right way of connecting to a socket ?Can anyone please suggest me ...
My code :
var app = express();
var dir = process.cwd();
app.use(express.static(dir)); //app public directory
app.use(express.static(__dirname)); //module directory
var server =require('http').createServer(app);
var io = require('socket.io')(server);
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
client code :
var socket = io('http://localhost:8085/socket_issue');
socket.on('connect', function(){ console.log('connected to socket'); });
socket.on('error', function(e){ console.log('error' + e); });
socket.on( 'news', function( data ){
console.log(data);
});
socket.on('disconnect', function(){});
You seem to not have a server.listen() in your backend code.
I've edited the server code and it functions correctly:
var app = require('express')();
var dir = process.cwd();
var server =require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
Don't forget to change the port on the front-end and it'll work as expected:
Socket connected :Y7zi7dLRxqBA5nakAAAA

Can't seem to get socket io to display any emits

I've been trying to figure out why I can't get any emits to show up in my terminal and it seems that everything is running fine.... except for seeing the emits. Here is my code
var express = require('express');
var path = require('path');
// Create a new Express application
var app = express();
var views = path.join(process.cwd(), 'views');
app.use("/static", express.static("public"));
// Create an http server with Node's HTTP module.
// Pass it the Express application, and listen on port 3000.
var server = require('http').createServer(app).listen(3000, function() {
console.log('listening on port ' + 3000)
});
// Instantiate Socket.IO hand have it listen on the Express/HTTP server
var io = require('socket.io')(server);
var game = require('./game');
app.get('/', function(req,res) {
res.sendFile(path.join(views, 'index.html'));
});
io.on('connect', function(socket) {
io.emit('connection', { message: "You are connected!" });
game.initGame(io, socket);
socket.emit('connected', { message: "You are connected!" });
io.sockets.emit('test', 'test')
});
Any help would be great!
Emits are not automatically printed. socket.emit will send a message back to the client, not to the terminal. Use console.log("whatever") to print to the terminal:
io.on('connect', function(socket) {
console.log('Client connected');
socket.on('test', function(data) {
console.log("Got message of type 'test'containing data:", data);
});
});

Routing with restify and socket.io in node

I have a node app which routes the request based on the url using restfy.
Now in want to bring socket into picture. But app doesnot redirect to the function when when socket.io is used. I am using FlexSocket.IO library in flex.
Here's my code snippet.
// In app.js
var restify = require('restify')
, http = require('http')
,socket = require('./routes/socket');
var app = restify.createServer();
app.get('/', socket.handle);
app.post('/', socket.handle);
var io = require('socket.io').listen(app);
app.listen(8080, function() {
console.log('%s listening at %s', app.name, app.url);
});
io.configure(function() {
io.set('transports', ['websocket','flashsocket']);
io.set('flash policy port', 843);
});
exports.io = io;
//In socket.js
exports.handle = function (req, res, next) {
console.log('In Handle'); //doesn't print this
io.sockets.on('connection', function(client){
console.log('Connection establiished');
});
In Flex
private var socket:FlashSocket;
socket = new FlashSocket("localhost:8080");
socket.addEventListener(FlashSocketEvent.CONNECT, onConnect);
socket.addEventListener(FlashSocketEvent.MESSAGE, onMessage);
protected function onConnect(event:FlashSocketEvent):void
{
Alert.show('connect'); //This alert is shown.
}
Is there anything wrong with the code? Why is the socket.handle function not called in node?
In app.js, try
var io = require('socket.io').listen(app.server); //app.server instead of just app

Resources