How to use web sockets - javascript

I'm trying to make use of Easy Websockets to come up with a chat application.
http://easywebsocket.org/
Here's the code I have right now. As you can see, I'm trying to log the message on the console every time I click on the send button. It works when I open it up on 2 browsers. But it only works for less than 1 minute.
<input type="text" id="txt"/>
<input type="button" value="send" id="sends"/>
<div id="messages"></div>
<script src="jquery171.js"></script>
<script src="easywebsockets.js"></script>
<script>
var socket = new EasyWebSocket("ws://sample.com/resource");//I do not understand this part
socket.onopen = function(){
socket.send("hello world.")
}
socket.onmessage= function(event){
console.log(event.data)
}
$('#sends').click(function(){
var txt = $('#txt').val()
socket.send(txt)
});
</script>
I got this error log from firebug:
I don't really understand what this all means. Is there something I need to setup in order to make this work?

It usually happens when the client doesn't use the same protocol version as the server. The server should specify what version it uses, socket.io by default goes with RFC6455 but it can be overridden to go with older hybi-0x.
So, check the following:
client & server implemented protocol versions
origin (e.g. localhost) is permitted by server
firewalls, internet security suites, zonealarms, that kind of stuff

Related

online offline check using javascript [duplicate]

This question already has answers here:
Detect the Internet connection is offline?
(22 answers)
Closed 8 years ago.
How do you check if there is an internet connection using jQuery? That way I could have some conditionals saying "use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection".
The best option for your specific case might be:
Right before your close </body> tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
This is probably the easiest way given that your issue is centered around jQuery.
If you wanted a more robust solution you could try:
var online = navigator.onLine;
Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.
Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.
I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.
What does it mean to be "online"?
There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.
To determine if a host is reachable from your network, you could do this:
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );
// Issue request and handle response
try {
xhr.send();
return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
} catch (error) {
return false;
}
}
You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579
Details on local implementation
Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.
Ok, maybe a bit late in the game but what about checking with an online image?
I mean, the OP needs to know if he needs to grab the Google CMD or the local JQ copy, but that doesn't mean the browser can't read Javascript no matter what, right?
<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}
var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>
Just my 2 cents
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.
You can mimic the Ping command.
Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.
If there's no response in 4 attempts, you can suppose that internet is down.
So you can check using this routine in regular intervals like 1 or 3 minutes.
That seems a good and clean solution for me.
You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.
I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.
http://tomriley.net/blog/archives/111
i have a solution who work here to check if internet connection exist :
$.ajax({
url: "http://www.google.com",
context: document.body,
error: function(jqXHR, exception) {
alert('Offline')
},
success: function() {
alert('Online')
}
})
Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.
You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:
<script type="text/javascript">
google.load("jquery");
// Call this function when the page has been loaded
function test_connection() {
if($){
//jQuery WAS loaded.
} else {
//jQuery failed to load. Grab the local copy.
}
}
google.setOnLoadCallback(test_connection);
</script>
The google API documentation can be found here.
A much simpler solution:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
and later in the code:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

Cookies not working when page accessed via file://

My code works in firefox and when i visit w3schools using chrome to test my code in their editor it works fine too but when i launch my code in chrome from notepad++ it doesn't work.It seems that body onload is not working because i don't get the alert.My chrome is up to date.Help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays){
var d=new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires="expires="+d.toUTCString();
document.cookie=cname +"="+cvalue+"; "+expires;
}
function f(){
var user=prompt("What is your name?","");
if(user!="" && user!=null){
setCookie("username",user,30);}
}
function getC(cname){
var name=cname+"=";
var ca=document.cookie.split(";");
for(var i=0;i<ca.length;i++){
var c=ca[i];
while(c.charAt(0)==" ")c=c.substring(1);
if(c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkcooki(){
var user=getC("username");
if(user!=""){
alert("Welcome back "+user);
}
}
</script>
</head>
<body onLoad="checkcooki()">
<input type="button" onclick="f()" value="klick">
</body>
</html>
For a fact: Using the file:// protocol does NOT guarantee the proper workings with cookies. Since cookies need 3 things:
A name-value pair containing the actual data
An expiry date after which it is no longer valid
The domain and path of the server it should be sent to
The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie.
On a file:// protocol you don't have a domain.
Now some browsers might have found work-arounds for this, like FireFox and IE. You can test your code on these browsers but they will not use cookies in the same way as on a webserver.
Proper x-browser testing in your case requires the http:// protocol.
I suggest you start a jsfiddle or setup a webserver(IIS, apache).
Proper read on cookies: quircksmode
If you are still persistent to get it working on chrome through the file:// protocol you might have a small chance if you get the path correctly.
path: properly escaped path => encodeURIComponent(document.domain) or "c:\/my%20folder\/index.html" (along these lines but again, very untrustworthy information here)
domain: "/" (no idea what else you can try here)
Your user variable must be a blank string.
Put an alert at the very top of your checkcooki() function to verify that body onload works.

ColdFusion 11 with websockets can't publish a message

I'm trying to get websockets working with ColdFusion. I am unable to send or receive messages and I am at a loss as to why. Am I missing something? Do I need to have any other programs installed? I am using Adobe ColdFusion Builder 3 Developer Edition.
Here is the code I am attempting to use.
Websocket.cfm
<cfwebsocket name="mycfwebsocketobject" onmessage="MessageHandler" subscribeto="stocks" >
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function MessageHandler(message)
{
alert(message.data);
}
function publishstock()
{
mycfwebsocketobject.Publish('stocks', 'I sent a message!');
}
setInterval('publishstock()',1000);
</script>
Application.cfc
<cfcomponent>
<cfset this.name="Websocket">
<cfset this.wschannels=[{name="stocks"}]>
</cfcomponent>
My goal is to get the MessageHandler function to trigger without explicitly calling it. I have no idea what is wrong and I have matched my code up perfectly with many examples on the web. I have been unsuccessful in both Chrome and Firefox.
I think that the real problem might have something to do with my machine. I found a demo online that worked perfectly, but when I downloaded the source it no longer worked. Is there a way to test for this?
Resources:
https://www.youtube.com/watch?v=Ys6BGrYJhNg
http://www.adobe.com/devnet/coldfusion/articles/html5-websockets-coldfusion-pt1.html
Your setInterval('publishstock()',1000);
Should be:
setInterval(function(){publishstock();},1000);

jQuery ajax get response not parsed or not seen

The problem is that jQuery does not receive the response by the server, and I can't figure out why. This is my setup, Windows 7 64bit:
ext.js:
$('#button').click(function(){
var string= $('#string').val();
$.get('http://localhost:3000',
{"input":string},
function(data){
alert(data);
$('#feedback').text(data);
});
})
099.html:
<doctype html>
<html lang="en">
<head> <!-- charset title style -->
<meta charset="uft-8"/>
<title>jQuery 099</title>
</head>
<body><!-- tables, div's bad, html 5 is better: -->
<input type="text" id="string" value=""/>
<input type="button" id="button" value="ajax"/>
<br/>
<div id="feedback"></div>
</body>
<script type="text/javascript" src="./js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="./js/ext.js"></script>
</html>
server.js:
var express = require('express');
var app = express();
app.get('/', function(req, res){
console.log("got");
console.log(req.query.input);
var content = req.query.input;
res.send(content);
});
app.listen(3000);
I run node 0.10 from command line using
C:\dev\nodejs\0.10\servers\stackoverflow>node server.js
In my FF browser i type
http://localhost:3000/?input=hi
and i get a blank screen containing hi,
which is good. Also node.js prints got and then hi on the command line
I run 099.html from notepad++ > run > chrome > so it runs on a completely other drive but surely it doesn't need to be in a server, right? When i type something XYZ the textfield and click ajax button, node responds on the console XYZ, which is good: the request is discovered by node, so it would send a response, but i don't see the response in my html.
The expected behavior was an alert and my div gets filled in the html and displays XYZ.
What obvious point am i missing?
I'm stuck for 2 hours now and couldnt find a similar question perhaps because of my not knowing jquery.
ps the 099 is from the newboston youtube tutorial and jquery is from the jquery site. i don't know the express version, it's a fairly new one.
ps2: the jquery $.get() api is too vague:http://api.jquery.com/jquery.get/ states: "A callback function that is executed if the request succeeds." well, can i conclude that the request succeeded because the nodejs console reacted to it, and if so, why did the callback function not execute.
ps3: the last argument is dataType, perhaps node responds in a way $.get did not expect? any datatype suggestions?
EDIT: yesterday i dusted off my tomcat and put the above files into it and jquery runs like a charm.
How stupid of me, assuming that a file on a disk can communicate over http to a server, what was i thinking.
the essence of ajax is "listening for the asynchronous response" (for example http://msdn.microsoft.com/en-us/magazine/cc163479.aspx), so the file needs to reside in something that establishes an IP address of some kind obviously. Sorry for polluting the Internet, case closed.
You cannot alter port number when issuing ajax request - this is Same origin policy restriction. See what you can do with SocketIO instead.

Angularjs' $http.get only executed once in IE11

I'm learning angularjs, and as a test project I'm polling a server that returns a list of active processes (their pids) and displaying these.
The client code looks like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/angular/angular.js"></script>
<script>
function ProcessCtrl($scope, $http, $interval) {
$scope.ReloadData = function() {
var result = $http.get("processdata", {timeout:1000});
result.success(function(data,status,headers,config) {
$scope.processes = data;
});
}
$scope.ReloadData();
var stop = $interval(function(){$scope.ReloadData()}, 1000);
}
</script>
</head>
<body ng-app>
<div ng-controller="ProcessCtrl">
Processes:
<ul>
<li ng-repeat="process in processes">
{{process.pid}} is running
</li>
</ul>
</div>
</body>
</html>
This works in Firefox and Chrome, but not quite in Internet Explorer 11.
All browsers execute the ReloadData method every second, but IE11 doesn't actually fetch the process data from the server. Firefox and Chrome do fetch the data every second. I can see this also in the output from my server, which logs every request.
All three browsers execute the code in result.success, but IE11 keeps reusing the old data it got the first time, where FireFox and Chrome use the newly fetched data.
I've checked the web console in IE11 for warnings or errors, but there are none.
Edit:
As the chosen answer suggested it was a caching problem. I have made the server add a 'cache-control' header to the response with the value 'no-cache'. This has solved the problem.
It's possible that the request is cached, as it is valid to cache GET requests. FF and Chrome probably have disabled caches, because of running dev tools or other reasons. You could append a timestamp as url query string "processdata?" + (new Date()).getTime() to see if it is a caching problem.
Prettier ways to prevent IE caching can be found here:
Angular IE Caching issue for $http
I prefer to use $http.post in order to prevent any cache.

Categories

Resources