dojo cometd is never ready - comet

I am trying to setup a Bayeux server and client using Jetty, Dojo and maven.
My issue is that dojo seems to never be ready. The callback in require is never called.
This is the code for the HTML page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script data-dojo-config="parseOnLoad:true" src="dojo/dojo.js.uncompressed.js"></script>
<script type="text/javascript">
function initFormListener( onNewForm ) {
require(["dojox/cometd", "dojo/io/script", "dojox/cometd/callbackPollTransport", "dojo/domReady!" ],
function ( cometd, io, callback ) {
console.log(" entered CometD function ");
// Function that manages the connection status with the Bayeux server
var _connected = false;
var _metaConnect = function ( message ) {
if ( cometd.isDisconnected() ) {
_connected = false;
console.log( "disconnected from server " + message );
return;
}
var wasConnected = _connected;
_connected = message.successful === true;
if ( !wasConnected && _connected ) {
console.log( "connected to server " );
}
else if ( wasConnected && !_connected ) {
console.log( "connection broken from server " + message );
}
}
// Function invoked when first contacting the server and
// when the server has lost the state of this client
var _metaHandshake = function ( handshake ) {
if ( handshake.successful === true ) {
cometd.batch( function () {
cometd.subscribe( '/newFormData', function ( message ) {
console.log( "new data for form " + message.formId + " in formData " + message.formDataId );
} );
} );
}
}
// Disconnect when the page unloads
dojo.addOnUnload( function () {
cometd.disconnect( true );
} );
var cometURL = location.protocol + "//" + location.host + "/VisionWeb/cometd";
cometd.configure( {
url:cometURL,
logLevel:'debug'
} );
cometd.addListener( '/meta/handshake', _metaHandshake );
cometd.addListener( '/meta/connect', _metaConnect );
cometd.handshake();
} );
}
initFormListener( function() {console.log("cometd success")});
</script>
</head>
<body>
just some content
</body>
</html>
It's not like dojo does not work on the server. It does. My app is written in dojo 1.7.2
Is there a known issue that I don't know about or am I doing something wrong?
Thank you for any tip on how to find out why the callback is never called.

You are trying to use cometD.
According to cometD's Reference Manual, you need to replace some js files of the standard Dojo toolkit, with the files provided in cometD's Primer download.
Use cometD's documentation and you'll get your app up and running nicely and in a reasonable time.

Related

How to implement service worker?

I have already been through different blogs explaning about service worker , one of them is open Web Push notification. I followed the instructions in Open Web Push notification and implemented a code which creates a curl registration id.Once the registration id is created i put it in database.but i get no notification . i normally enabled gcm in google console .
Should I also write gcm server and client code, as I have read a lot of blogs ,none said to do so.
what should i do to get notifications.
please refer below the codes if i have missed anything.
index.html
<!doctype html>
<html lang="en">
<head>
<title>Push Messaging & Notifications</title>
<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<link rel="icon" sizes="192x192" href="../images/touch/chrome-touch-icon-192x192.png">
<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-title" content="Push Messaging and Notifications Sample">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon-precomposed" href="../images/apple-touch-icon-precomposed.png">
<!-- Tile icon for Win8 (144x144 + tile color) -->
<meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#3372DF">
<link rel="icon" href="../images/favicon.ico">
<!-- Include manifest file in the page -->
<link rel="manifest" href="manifest.json">
<body>
<h1>Push Messaging & Notifications</h1>
<p>
<button class="js-push-button" disabled>
Enable Push Messages
</button>
</p>
<br />
<br />
<h2>cURL Command to Send Push</h2>
<div class="js-curl-command"></div>
<script src="config.js"></script>
<script src="demo.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
'use strict';
var API_KEY = window.GoogleSamples.Config.gcmAPIKey;
var GCM_ENDPOINT = 'https://android.googleapis.com/gcm/send';
var curlCommandDiv = document.querySelector('.js-curl-command');
var isPushEnabled = false;
// This method handles the removal of subscriptionId
// in Chrome 44 by concatenating the subscription Id
// to the subscription endpoint
function endpointWorkaround(pushSubscription) {
// Make sure we only mess with GCM
if (pushSubscription.endpoint.indexOf('https://android.googleapis.com/gcm/send') !== 0) {
return pushSubscription.endpoint;
}
var mergedEndpoint = pushSubscription.endpoint;
// Chrome 42 + 43 will not have the subscriptionId attached
// to the endpoint.
if (pushSubscription.subscriptionId &&
pushSubscription.endpoint.indexOf(pushSubscription.subscriptionId) === -1) {
// Handle version 42 where you have separate subId and Endpoint
mergedEndpoint = pushSubscription.endpoint + '/' +
pushSubscription.subscriptionId;
}
return mergedEndpoint;
}
function sendSubscriptionToServer(subscription) {
// TODO: Send the subscription.endpoint
// to your server and save it to send a
// push message at a later date
//
// For compatibly of Chrome 43, get the endpoint via
// endpointWorkaround(subscription)
var sub = subscription.endpoint;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "myusers.php?id="+sub, true);
xhttp.send();
console.log(subscription.endpoint);
var mergedEndpoint = endpointWorkaround(subscription);
// This is just for demo purposes / an easy to test by
// generating the appropriate cURL command
showCurlCommand(mergedEndpoint);
}
// NOTE: This code is only suitable for GCM endpoints,
// When another browser has a working version, alter
// this to send a PUSH request directly to the endpoint
function showCurlCommand(mergedEndpoint) {
// The curl command to trigger a push message straight from GCM
if (mergedEndpoint.indexOf(GCM_ENDPOINT) !== 0) {
window.Demo.debug.log('This browser isn\'t currently ' +
'supported for this demo');
return;
}
var endpointSections = mergedEndpoint.split('/');
var subscriptionId = endpointSections[endpointSections.length - 1];
var curlCommand = 'curl --header "Authorization: key=' + API_KEY +
'" --header Content-Type:"application/json" ' + GCM_ENDPOINT +
' -d "{\\"registration_ids\\":[\\"' + subscriptionId + '\\"]}"';
curlCommandDiv.textContent = curlCommand;
}
function unsubscribe() {
var pushButton = document.querySelector('.js-push-button');
pushButton.disabled = true;
curlCommandDiv.textContent = '';
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
// To unsubscribe from push messaging, you need get the
// subcription object, which you can call unsubscribe() on.
serviceWorkerRegistration.pushManager.getSubscription().then(
function (pushSubscription) {
// Check we have a subscription to unsubscribe
if (!pushSubscription) {
// No subscription object, so set the state
// to allow the user to subscribe to push
isPushEnabled = false;
pushButton.disabled = false;
pushButton.textContent = 'Enable Push Messages';
return;
}
// TODO: Make a request to your server to remove
// the users data from your data store so you
// don't attempt to send them push messages anymore
// We have a subcription, so call unsubscribe on it
pushSubscription.unsubscribe().then(function (successful) {
pushButton.disabled = false;
pushButton.textContent = 'Enable Push Messages';
isPushEnabled = false;
}).catch(function (e) {
// We failed to unsubscribe, this can lead to
// an unusual state, so may be best to remove
// the subscription id from your data store and
// inform the user that you disabled push
window.Demo.debug.log('Unsubscription error: ', e);
pushButton.disabled = false;
});
}).catch(function (e) {
window.Demo.debug.log('Error thrown while unsubscribing from ' +
'push messaging.', e);
});
});
}
function subscribe() {
// Disable the button so it can't be changed while
// we process the permission request
var pushButton = document.querySelector('.js-push-button');
pushButton.disabled = true;
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe({ userVisibleOnly: true })
.then(function (subscription) {
// The subscription was successful
isPushEnabled = true;
pushButton.textContent = 'Disable Push Messages';
pushButton.disabled = false;
// TODO: Send the subscription subscription.endpoint
// to your server and save it to send a push message
// at a later date
return sendSubscriptionToServer(subscription);
})
.catch(function (e) {
if (Notification.permission === 'denied') {
// The user denied the notification permission which
// means we failed to subscribe and the user will need
// to manually change the notification permission to
// subscribe to push messages
window.Demo.debug.log('Permission for Notifications was denied');
pushButton.disabled = true;
} else {
// A problem occurred with the subscription, this can
// often be down to an issue or lack of the gcm_sender_id
// and / or gcm_user_visible_only
window.Demo.debug.log('Unable to subscribe to push.', e);
pushButton.disabled = false;
pushButton.textContent = 'Enable Push Messages';
}
});
});
}
// Once the service worker is registered set the initial state
function initialiseState() {
// Are Notifications supported in the service worker?
if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
window.Demo.debug.log('Notifications aren\'t supported.');
return;
}
// Check the current Notification permission.
// If its denied, it's a permanent block until the
// user changes the permission
if (Notification.permission === 'denied') {
window.Demo.debug.log('The user has blocked notifications.');
return;
}
// Check if push messaging is supported
if (!('PushManager' in window)) {
window.Demo.debug.log('Push messaging isn\'t supported.');
return;
}
// We need the service worker registration to check for a subscription
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
// Do we already have a push message subscription?
serviceWorkerRegistration.pushManager.getSubscription()
.then(function (subscription) {
// Enable any UI which subscribes / unsubscribes from
// push messages.
var pushButton = document.querySelector('.js-push-button');
pushButton.disabled = false;
if (!subscription) {
// We aren’t subscribed to push, so set UI
// to allow the user to enable push
return;
}
// Keep your server in sync with the latest subscription
sendSubscriptionToServer(subscription);
// Set your UI to show they have subscribed for
// push messages
pushButton.textContent = 'Disable Push Messages';
isPushEnabled = true;
})
.catch(function (err) {
window.Demo.debug.log('Error during getSubscription()', err);
});
});
}
window.addEventListener('load', function () {
var pushButton = document.querySelector('.js-push-button');
pushButton.addEventListener('click', function () {
if (isPushEnabled) {
unsubscribe();
} else {
subscribe();
}
});
// Check that service workers are supported, if so, progressively
// enhance and add push messaging support, otherwise continue without it.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(initialiseState);
} else {
window.Demo.debug.log('Service workers aren\'t supported in this browser.');
}
});
config.js
window.GoogleSamples = window.GoogleSamples || {};
window.GoogleSamples.Config = window.GoogleSamples.Config || {
gcmAPIKey: '<Your Public API Key ...>'
};
service-worker.js
'use strict';
self.addEventListener('push', function (event) {
console.log('Received a push message', event);
var title = 'Yay a message.';
var body = 'We have received a push message.';
var icon = '/images/icon-192x192.png';
var tag = 'simple-push-demo-notification-tag';
event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
);
});
self.addEventListener('notificationclick', function (event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn’t close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
type: "window"
}).then(function (clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow('/');
}));
});
demo.js
'use strict';
function Debug() {
}
Debug.prototype.log = function () {
var paragraphElement = document.createElement('p');
paragraphElement.textContent = Array.prototype.join.call(arguments, '');
document.querySelector('.js-log').appendChild(paragraphElement);
}
window.addEventListener('load', function () {
var logDiv = document.createElement('div');
logDiv.classList.add('js-log');
var heading = document.createElement('h2');
heading.textContent = 'Log';
logDiv.appendChild(heading);
document.body.appendChild(logDiv);
window.Demo = window.Demo || {};
window.Demo.debug = window.Demo.debug || new Debug();
});
after writing all this code what else can be done ??
I have not worked with gcm so finding hard time enabling,need help.
Yes, writing server-side code is required for "real" use cases. The curl command is just meant as a one-off test of the functionality.
https://github.com/gauntface/simple-push-demo is a good server-side starting point, assuming a Python App Engine backend.
Some examples
https://github.com/beverloo/peter.sh/tree/master/tests has very basic php version of the server side code. You can ignore all the encryption related stuff since that is only needed if you need to send payloads.
https://github.com/johnmellor/push-api-appengine-demo contains a python server side implementation which you can try in https://johnme-gcm.appspot.com/chat/
The actual sending code is pretty straight forward. Just send a JSON requests that looks like this
{
'registration_ids': registration_ids,
'collapse_key': "constantString",
}
Via a POST message to https://android.googleapis.com/gcm/send
The full API and some more examples (not specific to web push but still useful) in https://developers.google.com/cloud-messaging/

Couldn't make ASPJAX working

I want to make a demo on how to combine ASP and AJAX. I have found snippets from http://www.aspjax.com and implemented it in my project. However, the text that should be displayed cannot be output properly.
Here's the code. Basically the same as the one in the original:
In index.asp
<script language="javascript" type="text/javascript">
/** XHConn - Simple XMLHTTP Interface - bfults#gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
// doAJAXCall : Generic AJAX Handler, used with XHConn
// Author : Bryce Christensen (www.esonica.com)
// PageURL : the server side page we are calling
// ReqType : either POST or GET, typically POST
// PostStr : parameter passed in a query string format 'param1=foo&param2=bar'
// FunctionName : the JS function that will handle the response
var doAJAXCall = function (PageURL, ReqType, PostStr, FunctionName) {
// create the new object for doing the XMLHTTP Request
var myConn = new XHConn();
// check if the browser supports it
if (myConn) {
// XMLHTTPRequest is supported by the browser, continue with the request
myConn.connect('' + PageURL + '', '' + ReqType + '', '' + PostStr + '', FunctionName);
}
else {
// Not support by this browser, alert the user
alert("XMLHTTP not available. Try a newer/better browser, this application will not work!");
}
}
// launched from button click
var getMessage = function () {
// build up the post string when passing variables to the server side page
var PostStr = "";
// use the generic function to make the request
doAJAXCall('ajaxtest.asp', 'POST', '', showMessageResponse);
}
// The function for handling the response from the server
var showMessageResponse = function (oXML) {
// get the response text, into a variable
var response = oXML.responseText;
// update the Div to show the result from the server
document.getElementById("responseDiv").innerHTML = response;
};
</script>
<body>
<button onclick="javascript:getMessage();">Get Message From Server</button>
<div id="responseDiv">Original Text</div>
</body>
So, the code tells it to replace the Original Text in the div with the one in ajaxtest.asp
In ajaxtest.asp
<%# Language=VBScript %>
Response.Write "The Server time is " & Now()
The problem is when I click the button Get Message From Server, the stuff in ajaxtest.asp is rendered as plain text, but not in ASP. How to fix this? Is it because of the extension used is wrong?
EDIT: by plain text I mean exactly as Response.Write "The Server time is " & Now()
You probably want the contents of your ASP page to be:
<%# Language=VBScript %>
The Server time is <%=Now()%>

Parallel form submit and ajax call

I have a web page that invokes long request on the server. The request generates an excel file and stream it back to the client when it is ready.
The request is invoked by creating form element using jQuery and invoking the submit method.
I would like during the request is being processed to display the user with progress of the task.
I thought to do it using jQuery ajax call to service I have on the server that returns status messages.
My problem is that when I am calling this service (using $.ajax) The callback is being called only when the request intiated by the form submit ended.
Any suggestions ?
The code:
<script>
function dummyFunction(){
var notificationContextId = "someid";
var url = $fdbUI.config.baseUrl() + "/Promis/GenerateExcel.aspx";
var $form = $('<form action="' + url + '" method="POST" target="_blank"></form>');
var $hidden = $("<input type='hidden' name='viewModel'/>");
$hidden.val(self.toJSON());
$hidden.appendTo($form);
var $contextId = new $("<input type='hidden' name='notifyContextId'/>").val(notificationContextId);
$contextId.appendTo($form);
$('body').append($form);
self.progressMessages([]);
$fdbUI.notificationHelper.getNotifications(notificationContextId, function (message) {
var messageText = '';
if (message.IsEnded) {
messageText = "Excel is ready to download";
} else if (message.IsError) {
messageText = "An error occured while preparing excel file. Please try again...";
} else {
messageText = message.NotifyData;
}
self.progressMessages.push(messageText);
});
$form.submit();
}
<script>
The code is using utility library that invokes the $.ajax. Its code is:
(function () {
if (!window.flowdbUI) {
throw ("missing reference to flowdb.ui.core.");
}
function NotificationHelper() {
var self = this;
this.intervalId = null;
this.getNotifications = function (contextId, fnCallback) {
if ($.isFunction(fnCallback) == false)
return;
self.intervalId = setInterval(function() {
self._startNotificationPolling(contextId, fnCallback);
}, 500);
};
this._startNotificationPolling = function (contextId, fnCallback) {
if (self._processing)
return;
self._processing = true;
self._notificationPolling(contextId, function (result) {
if (result.success) {
var message = result.retVal;
if (message == null)
return;
if (message.IsEnded || message.IsError) {
clearInterval(self.intervalId);
}
fnCallback(message);
} else {
clearInterval(self.intervalId);
fnCallback({NotifyData:null, IsEnded:false, IsError:true});
}
self._processing = false;
});
};
this._notificationPolling = function (contextId, fnCallback) {
$fdbUI.core.executeAjax("NotificationProvider", { id: contextId }, function(result) {
fnCallback(result);
});
};
return this;
}
window.flowdbUI.notificationHelper = new NotificationHelper();
})();
By default, ASP.NET will only allow a single concurrent request per session, to avoid race conditions. So the server is not responding to your status requests until after the long-polling request is complete.
One possible approach would be to make your form post return immediately, and when the status request shows completion, start up a new request to get the data that it knows is waiting for it on the server.
Or you could try changing the EnableSessionState settings to allow multiple concurrent requests, as described here.

HTML5 Web SQL keeps making duplicates and breaks the old database

I'm making a database application for Safari purely. So I'm following this guide made by Apple: Link.
I have made this "class" prototype so far. It works, but it keeps making duplicates of the database (they just keep stacking up in the Safari Inspector tool) (without me changing the version from 1.0):
function Database() {
this.DB = null;
this.shortName = 'gamedb';
this.version = '1.0';
this.displayName = 'Database';
this.maxSize = 5 * 1024 * 1024;
init: (function() {
})
this.initDB = function() {
try {
if (!window.openDatabase) {
alert('Error: Databases are not supported.');
}
else {
this.DB = openDatabase(this.shortName, this.version, this.displayName, this.maxSize);
}
return true;
}
catch(e) {
if (e == 2) {
// Version number mismatch.
console.log("Error: Invalid database version.");
}
else {
console.log("Error: Unknown, " + e + ".");
}
return;
}
}
this.query = function(query) {
if (query == undefined) {
query = '';
}
query = query + ';'; // Add the ending semi-colon
this.DB.transaction(
function (transaction) {
transaction.executeSql(
query,
[],
this.nullDataHandler,
this.errorHandler
);
}
);
}
this.nullDataHandler = function() {
return 0;
}
this.errorHandler = function(error) {
return 0;
}
}
And here's my main.js file with my jQuery handle and the instantiation of the Database prototype:
$(document).ready(function() {
var DB = new Database();
DB.initDB();
DB.query('CREATE TABLE IF NOT EXISTS users(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)');
DB.query('INSERT INTO users(name) VALUES ("Jackson")');
});
Even just blankly running this line creates duplicates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>X</title>
<style>
html, body {
background: #202020;
color: #8d9d6a;
}
</style>
<script type="text/javascript">
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
var db = openDatabase(shortName, version, displayName, maxSize);
</script>
</head>
<body>
Content
</body>
</html>
Notes:
I have Extensions turned off
No changes in the Developer menu (nothing disabled or blocked)
I had this problem in both chrome and safari. When I saved a record it would appear several times and the inspector would show duplicates of the webSQL db (50 or more!). For me it turned out that I was calling a SELECT too soon after the save in order to update the view. I moved it into a success function and that fixed the problem. I can only think that the browser gets confused and spawns multiple DBs in the inspector. This might not be the same problem but it seemed close enough to mention.
Side information for anyone as new to this as myself.
I had a query selecting from more than one table which caused my display to duplicate. Stupid problem, simple fix by obviously selecting a single table
var showLearnerSQL = "SELECT * FROM tblLearnerInfo, tblDrive";// Not a great idea
var showLearnerSQL = "SELECT * FROM tblLearnerInfo; // Great idea

Socket.IO Websocket Send message not working with Firefox and Chrome

I have a running server with apache and Socket.IO. I'm trying to send and receive message using socket.io on my website.
This is the code of my server:
var fs = require('fs');
var hskey = fs.readFileSync('file.key');
var hscert = fs.readFileSync('file.crt');
var options = {
key: hskey,
cert: hscert
};
var app = require('https').createServer(options);
var io = require('/usr/local/lib/node_modules/socket.io').listen(app);
app.listen(8181);
io.sockets.on('connection', function (socket) {
socket.emit('serverMessage', 'Bienvenue master!');
socket.broadcast.emit('serverMessage', 'New user online');
});
And this is the webpage:
<!doctype html>
<html>
<head>
<title>Socket.io Test</title>
<script src="./socket.io.js"></script>
</head>
<body>
<script>
var socket;
var firstconnect = true;
function connect() {
if(firstconnect) {
socket = io.connect('https://secure.mysite.com:8181');
socket.on('serverMessage', function(data){ message(data); });
socket.on('connect', function(){ status_update("Connected to Server"); });
socket.on('disconnect', function(){ status_update("Disconnected from Server"); });
socket.on('reconnect', function(){ status_update("Reconnected to Server"); });
socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in "
+ nextRetry + " seconds"); });
socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });
firstconnect = false;
}
else {
socket.socket.reconnect();
}
}
function disconnect() {
socket.disconnect();
}
function message(data) {
document.getElementById('message').innerHTML += "<br>" + "Server says: " + data;
}
function status_update(txt){
document.getElementById('status').innerHTML = txt;
}
function esc(msg){
return msg.replace(/</g, '<').replace(/>/g, '>');
}
function send() {
socket.send('clientMessage', 'world');
};
</script>
<h1>Socket.io Test</h1>
<div><p id="status">Waiting for input</p></div>
<div><p id="message"></p></div>
<button id="connect" onClick='connect()'/>Connect</button>
<button id="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body>
</html>
Everything seems to work fine under Safari (websocket) and Opera (json pooling) but with Firefox and Chrome (websocket) I cannot send any message from the client to the server. Everything else is working, I can handshake, connect and gets server messages. I made allot of research but seems like I'm the only one with this problem.
Thanks for helping me!
I found the problem, I was using a different version of socket.io.js then the server side.
when you attach the socket.io module to express it intercepts the socket.io route.
So when you request "https://secure.mysite.com:8181/socket.io" it will respond with
"Welcome to socket.io."
So when you request the client side socket.io.js it comes directly from the socket.io module.
"https://secure.mysite.com:8181/socket.io/socket.io.js"
So If you wan't to mod the client side library you could create a modified copy and let express serve up the file, but as you update socketio through npm you'll have to bump up your modified copy as well manually.
if in FireFox you get this error - first check enabled or no proxy. and turnoff proxy if enabled.