ejabberd XMPP connection failed using strophejs - xmpp

I am trying to run THIS XMPP JS code using ejabberd on server side. Here is my connection code:
$(document).bind('connect', function (ev, data) {
console.log("connect "+JSON.stringify(data));
var conn = new Strophe.Connection("http://localhost:5280/http-bind");
conn.connect(data.jid, data.password, function (status) {
console.log("status"+status);
if (status === Strophe.Status.CONNECTED) {
$(document).trigger('connected');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
}
});
Hello.connection = conn;
});
I am getting status = 1. and after few time later it starts keep showing :
Uncaught Error: 11, flXHR::abort(): Failed, The abort() call failed to complete.
My ejabberd is running on http://localhost:5280/admin/ and admin#ejab is admin user.
Here is full code:
<!DOCTYPE html>
<html>
<head>
<title>Strophe.js Basic Example</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'></script>
<script src='../strophe.js'></script>
<!-- <script src='scripts/flXHR.js'></script>
<script src='scripts/strophe.flxhr.js'></script>-->
<script src='basic.js'></script>
</head>
<body>
<div id='login' style='text-align: center'>
<form name='cred'>
<label for='jid'>JID:</label>
<input type='text' id='jid'>
<label for='pass'>Password:</label>
<input type='password' id='pass'>
<input type='button' id='connect' value='connect'>
</form>
</div>
<hr>
<div id='log'></div>
</body>
</html>
basic.js
var BOSH_SERVICE = 'http://localhost:5222/http-bind';
var connection = null;
function log(msg)
{
$('#log').append('<div></div>').append(document.createTextNode(msg));
}
function rawInput(data)
{
log('RECV: ' + data);
}
function rawOutput(data)
{
log('SENT: ' + data);
}
function onConnect(status)
{
if (status == Strophe.Status.CONNECTING) {
log('Strophe is connecting.');
} else if (status == Strophe.Status.CONNFAIL) {
log('Strophe failed to connect.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.DISCONNECTING) {
log('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
log('Strophe is disconnected.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.CONNECTED) {
log('Strophe is connected.');
connection.disconnect();
}
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.rawInput = rawInput;
connection.rawOutput = rawOutput;
$('#connect').bind('click', function () {
var button = $('#connect').get(0);
if (button.value == 'connect') {
button.value = 'disconnect';
connection.connect($('#jid').get(0).value,
$('#pass').get(0).value,
onConnect);
} else {
button.value = 'connect';
connection.disconnect();
}
});
});
ouput is :
Strophe is connecting.
SENT: <body rid='745165534' xmlns='http://jabber.org/protocol/httpbind' to='ejab' xml:lang='en' wait='60' hold='1' content='text/xml; charset=utf-8' ver='1.6' xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'/>

status = 1 means connecting. It mostly means BOSH server cannot be reached.
Type in
http://localhost:5280/http-bind/
at Chrome to see if you can really reach the BOSH server.
If your server is really host at localhost (your computer where hello.html stored), you can comment out the
flXHR.js and strophe.flxhr.js at hello.html's header as they are for cross domain access.
e.g. hello.html at your desktop and using a domain(xmpp server) that host at another computer which are not allowed by Chrome due to cross domain access security already.
If both hello.html and xmpp server are located at the same computer, it won't have cross domain issue.
Anyway, these 2 files seem not able to overcome the cross domain access limit set by Chrome browser a few years back. Use Chrome's parameter "--disable-web-security" can provide cross domain access for test.
Lastly, at Chrome browser, right click to select "Inspect Element" -> Network, reload the hello.html and login to check those http-bind access. They should give hint on what goes wrong.

Related

Angular2/Nativescript: TypeError from a Rest service that works without any issues in a web app

I am busy with a small app that talks to a local server. When the app starts I check for a IP address in LocalStorage using the Nativescript-localstorage module... If the IP hasn't been set the app then navigates to a settings view where the IP can be entered. When the IP is entered and a submit button is tapped the IP is used in a GET method of a /ping enddpoint of a Rest service that confirms that the correct IP was entered/that the server is up... I keep getting the following error:
error:
TypeError: error.json is not a function
i'm guessing this happens in my Rest service's ping function but can't figure out why... This service works fine with no errors in another web app. Any idea what could be causing this?
UPDATE:
So it seems like I only get this error when entering the correct IP. When I enter a random incorrect IP I get 'server error' as the response...
my code:
settings.component.ts:
import { Component,} from '#angular/core';
import { RestService } from '../../services/rest.service';
import { LocalStorageService } from '../../services/local-storage.service';
#Component({
selector: 'settings',
templateUrl: './pages/settings/settings.component.html'
})
export class SettingsComponent {
ipSaved: boolean = false;
error: boolean = false;
ip: string;
constructor(private restService: RestService, private localStorageService: LocalStorageService) {
}
submitIP() {
if (this.ip !== null && this.ip !== ''){
console.log("ip before get: " + this.ip);
this.restService.ping(this.ip)
.subscribe(
(res) => {
this.localStorageService.saveLocalIP(this.ip);
this.restService.init(this.ip);
this.ipSaved = true;
},
(res) => {
console.log(res);
this.error = true;
}
);
console.log("ip: " + this.localStorageService.findLocalIP());
} else {
alert("Warning: IP field can't be empty!");
}
}
dismissError() {
this.error = false;
}
}
settings.component.html:
<StackLayout class="page">
<Label class="h1 title m-x-auto " text="Settings"></Label>
<StackLayout class="form" *ngIf="!IPSaved && !error">
<StackLayout class="input-field">
<TextField class="input input-border" placeholder="Enter IP" [(ngModel)]="ip"></TextField>
</StackLayout>
<Button class="btn btn-primary" text="Submit" (tap)="submitIP()"></Button>
</StackLayout>
<StackLayout *ngIf="IPSaved && !error">
<Label class="h1" text="IP Saved successfully"></Label>
<Button class="btn btn-primary" text="Done" [nsRouterLink]="['/home']"></Button>
</StackLayout>
<StackLayout *ngIf="error">
<Label class="body text-danger" text="ERROR: The IP address entered doesn't seem to be correct. Make sure the device is connected to the local wireless network and try again..."></Label>
<Button class="btn btn-primary" (tap)="dismissError()"></Button>
</StackLayout>
</StackLayout>
my ping function from my rest.service.ts:
ping(ip: string) : Observable<Response> {
let tempApiUrl: string = "http://" + ip + "/BRMServices/WebEnquiry/ping";
return this.http.get(tempApiUrl, this.headers)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
Have a look at the type of the error object in the catch block. In your code it is of type any which is invalid. Instead it should also be of type Response as below.
ping(ip: string) : Observable<Response> {
let tempApiUrl: string = "http://" + ip + "/BRMServices/WebEnquiry/ping";
return this.http.get(tempApiUrl, this.headers)
.map((res: Response) => res.json())
// below line is modified
.catch((error: Response) => Observable.throw(error.json().error || 'Server error'));
}

Can't connect to OpenFire using Strophe.js on Localhost

I installed OpenFire on my localhost and have enabled Bosh connection over http on port 7070. I downloaded the latest strophe.js and flXHR.js for connection and cross-domain connection but so far, it has failed to connect successfully.
I have searched SO for answers, I tried them but still no success.
Below is my code;
$(document).bind("connect", function (ev, data) {
var conn = new Strophe.Connection("http://127.0.0.1:7070/http-bind/");
conn.connect(data.jid, data.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger("connected");
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger("disconnected");
}
Hello.connection = conn;
conn.rawOutput = log;
conn.rawInput = log;
});
});
$(document).bind("connected", function () {
// inform the user
Hello.log("Connection established.");
});
$(document).bind("disconnected", function () {
Hello.log("Connection terminated.");
// remove dead connection object
Hello.connection = null;
});
function log(msg) {
console.log(msg);
}
function rawInput(data) {
log("RECV: " + data);
Hello.log("RECV: " + data);
}
function rawOutput(data) {
log("SENT: " + data);
Hello.log("SENT: " + data);
}
LOG
<body rid='3424369325' xmlns='http://jabber.org/protocol/httpbind' to='127.0.0.1' xml:lang='en' wait='60' hold='1' content='text/xml; charset=utf-8' ver='1.6' xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'/>
<body xmlns='http://jabber.org/protocol/httpbind' xmlns:stream='http://etherx.jabber.org/streams' from='localhost' authid='f8443751' sid='f8443751' secure='true' requests='2' inactivity='30' polling='5' wait='60' hold='1' ack='3424369325' maxpause='300' ver='1.6'><stream:features><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>DIGEST-MD5</mechanism><mechanism>PLAIN</mechanism><mechanism>CRAM-MD5</mechanism></mechanisms><compression xmlns='http://jabber.org/features/compress'><method>zlib</method></compression><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/><session xmlns='urn:ietf:params:xml:ns:xmpp-session'/></stream:features></body>
<body rid='3424369326' xmlns='http://jabber.org/protocol/httpbind' sid='f8443751'><auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/></body>
POST http://127.0.0.1:7070/http-bind/ 500 (Server Error)
I am getting this 500 Error. Is there anything I am doing wrong?

Two near-identical forms functioning differently

I have two nearly identical forms on two different pages which take in a user's name and email address. When I press the submit button, both of them call a validator, which works correctly, and then both are supposed to make an Ajax call and display the results. At this point, one of them makes the call successfully, and the other simply refreshes the page. I'm not sure what the difference is that causes one to work successfully and the other to fail. With the one that works, I already had this problem once with the form that works, which was caused by me generating the form through javascript. I have no idea what is causing it now. Here is the inline code for the functioning one:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var invites = <?php echo $user->getInvitesLeft(); ?>;
</script>
</form>
</div>
Response is where it displays the response from the Ajax call. I have to generate the content later on using Javascript because I take different actions depending on the value of invites. I was originally generating the whole thing, but I found that I had to have the form tags in place to prevent the refreshing problem the first time. Here is the code that generates the form the user sees:
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator function:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
}
else{
$("#inviteModal .response").text(data);
}
}
}); //End ajax
} //End submitHandler
}); //End validator
As I said, this one works perfectly fine. The only difference between this one and the one that refreshes is that the non-functioning one is on a page that you don't have to be logged in to see, and takes different actions depending on whether or not a user is logged in. Here is the inline code:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<?php
if(!$user || $user == null){ //No user logged in, display invite request form instead
$loggedin = false;
}
else{ //Allow user to invite friends
$loggedin = true;
}
?>
</form>
Here is the generation code, almost identical except for one extra if layer:
if(!loggedin){
$("#inviteForm").html("<h2>Please enter the specified information to request an invitation. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
else{
invites = <?php echo $user->getInvitesLeft(); ?>;
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
if(loggedIn){ //They are inviting a friend
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
//$("#overlay").css("display", "none");
//$("#inviteModal").fadeOut(5000);
}
else{
$("#inviteModal .response").text(data);
}
return false;
}
}); //End Ajax
}
else{ //They are requesting an invite for theirself
$.ajax({
type: "POST",
url: '/invite/request',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
$("#inviteModal .response").text(data);
return false;
}
}); //End ajax
}
return false;
} //End submitHandler
}); //End validate
Again almost identical except for one extra layer of if. So why would the bottom one refresh the page instead of making the Ajax call while the first one works perfectly fine?
how about commenting out those return false statement in the ajax success callback functions for the second one?

Looking for working example of WP7 PhoneGap Facebook plugin for signin button

I've tried all the code at https://github.com/davejohnson/phonegap-plugin-facebook-connect
that is recommended by the phonegap community, but i keep running into errors trying to get it to work.
As you can see I'm using cordova 1.6.0 which maybe the problem?
i've added the script files to in my html page
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js"></script>
<script type="text/javascript" charset="utf-8" src="cdv-plugin-fb-connect.js">/script>
<script type="text/javascript" charset="utf-8" src="facebook_js_sdk.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
And I've added the ChildBrowserCommand.cs into the plugins directory.
I then added this to device ready listener with my authentic app id (the real id not shown here)
document.addEventListener("deviceready",onDeviceReady,false);
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady() {
//document.getElementById("welcomeMsg").innerHTML += "Cordova is ready! version=" + window.device.cordova;
console.log("onDeviceReady. You should see this message in Visual Studio's output window.");
//fb connect sign in
try {
//alert('Device is ready! Make sure you set your app_id below this alert.');
console.log('Device is ready! Make sure you set your app_id below this alert.');
FB.Cookie.setEnabled(true); // this seems to be duplicate to 'cookie: true' below, but it is IMPORTANT due to FB implementation logic.
FB.init({ appId: "311961255484993", nativeInterface: CDV.FB, cookie: true });
login();
} catch (e) {
//alert(e);
console.log("Init error: " + e);
}
};
function login() {
FB.login(
function (response) {
if (response.session) {
console.log('logged in');
} else {
console.log('not logged in');
}
},
{ scope: 'email, read_stream, read_friendlists' }
);
}
The error i get is
Unable to locate command :: org.apache.cordova.facebook.Connect
Any help?
EDIT: I also realize it's coming from cdv-plugin-fb-connect.js in here but not sure why?
cordova.exec(function () {
var authResponse = JSON.parse(localStorage.getItem('cdv_fb_session') || '{"expiresIn":0}');
if (authResponse && authResponse.expirationTime) {
var nowTime = (new Date()).getTime();
if (authResponse.expirationTime > nowTime) {
// Update expires in information
updatedExpiresIn = Math.floor((authResponse.expirationTime - nowTime) / 1000);
authResponse.expiresIn = updatedExpiresIn;
localStorage.setItem('cdv_fb_session', JSON.stringify(authResponse));
FB.Auth.setAuthResponse(authResponse, 'connected');
}
}
console.log('Cordova Facebook Connect plugin initialized successfully.');
}, (fail ? fail : null), 'org.apache.cordova.facebook.Connect', 'init', [apiKey]);
},

WebSockets on iOS

I've read that WebSockets work on iOS 4.2 and above. And I can verify that there is indeed a WebSocket object. But I can't find a single working WebSocket example that works on the phone.
For example http://yaws.hyber.org/websockets_example.yaws will crash the Mobile Safari app. Has anyone got WebSockets working successfully on the phone?
I may have found the solution. Mobile Safari only crashes with websockets when you have setup a proxy over wifi.
It is supported, but bear in mind regarding the standard that iOS Safari browser implements, it is not RFC 6455, but HyBi-00/Hixie-76.
You can test as well using this browser: http://websocketstest.com/
As well check this great post that have most of info regarding versions: https://stackoverflow.com/a/2700609/1312722
OBS!, this is an old answer.
I have checked through the webpage mentioned in this post combined with browserstack.com:
iPhone4S
iPhone5
iPhone5S
iPhone6
iPhone6 Plus
iPhone6S
iPhone6S Plus
All using RFC 6455
I had a similar problem and even looked to this post to find a fix for it. For me, it had nothing to do with being on a wifi connection. It appears to be a bug in the iOS implementation of websockets (even up to the current version 5.1). Turning on a bunch of XCode's debugging I found that it has something to do with memory management because I would get something along the lines of "message sent to a deallocated instance." Most likely there was an object that didn't have the correct reference count and was cleaned up way too early.
This blog has a lot of great information about the symptoms of the problem and how to debug it, but doesn't have a workaround: http://dalelane.co.uk/blog/?p=1652
Eventually though, I found this workaround, and my app has almost entirely stopped crashing now.
me = this // strange javascript convention
this.socket = new WebSocket(url);
// put onmessage function in setTimeout to get around ios websocket crash
this.socket.onmessage = function(evt) { setTimeout(function() {me.onMessageHandler(evt);}, 0); };
I got them working on Chrome and Safari, iPhone and iPad (and other mobile devices too, but I guess you don't mind about them). Here is the Javascript code I am using :
<script language="javascript" type="text/javascript">
var wsUri = document.URL.replace("http", "ws");
var output;
var websocket;
function init()
{
output = document.getElementById("output");
wsConnect();
}
function wsConnect()
{
console.log("Trying connection to " + wsUri);
try
{
output = document.getElementById("output");
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt)
{
onOpen(evt)
};
websocket.onclose = function(evt)
{
onClose(evt)
};
websocket.onmessage = function(evt)
{
onMessage(evt)
};
websocket.onerror = function(evt)
{
onError(evt)
};
}
catch (e)
{
console.log("Exception " + e.toString());
}
}
function onOpen(evt)
{
alert("Connected to " + wsUri);
}
function onClose(evt)
{
alert("Disconnected");
}
function onMessage(evt)
{
alert('Received message : ' + evt.data);
}
function onError(evt)
{
alert("Error : " + evt.toString());
}
function doSend(message)
{
websocket.send(message);
}
window.addEventListener("load", init, false);
Sending data from client to server is done calling doSend() function. Receiving data from server also works, I've tested it from a custom C++ server.
Here is a working sample
Web socket client
<!DOCTYPE html>
<meta charset="utf-8" />
<head>
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var websocket;
function OpenWebSocket()
{
try {
websocket = new WebSocket(document.getElementById("wsURL").value);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
catch(err) {
writeToScreen(err.message);
}
}
function CloseWebSocket()
{
websocket.close();
}
function FindWebSocketStatus()
{
try {
if (websocket.readyState == 1){
writeToScreen("Websocket connection is in open state")
}
else if (websocket.readyState == 0){
writeToScreen("Websocket connection is in connecting state")
}
else{
writeToScreen("Websocket connection is in close state")
}
}
catch(err) {
writeToScreen(err.message);
}
}
function FindWebSocketBufferedAmount(){
try {
writeToScreen(websocket.bufferedAmount)
}
catch(err) {
writeToScreen(err.message);
}
}
function SendMessageThroughSocket(){
doSend(document.getElementById("wsMessage").value);
}
function onOpen(evt)
{
writeToScreen("Socket Connection Opened");
}
function onClose(evt)
{
writeToScreen("Socket Connection Closed");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">SERVER RESPONSE: ' + evt.data+'</span>');
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
try{
writeToScreen("CLIENT SENT: " + message);
websocket.send(message);
}
catch(err) {
writeToScreen(err.message);
}
}
function writeToScreen(message)
{
var output = document.getElementById("output");
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
</script>
</title>
</head>
<body>
<table>
<tr>
<td>
WebSocket URL
</td>
<td>
<input type="text" id="wsURL" value="ws://echo.websocket.org/"/>
</td>
</tr>
<tr>
<td>
WebSocket Message
</td>
<td>
<input type="text" id="wsMessage" value="Hi"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Open Socket Connection" onclick="OpenWebSocket();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Send Message" onclick="SendMessageThroughSocket();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Close Socket Connection" onclick="CloseWebSocket();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Find Socket Status" onclick="FindWebSocketStatus();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Find Socket Buffered Amount" onclick="FindWebSocketBufferedAmount();"/>
</td>
</tr>
</table>
<div id="output"></div>
</body>
</html>
Web Socket server
Creating your own socket server is also simple Just install the Node.js and socket.io then proceed to install web socket via npm
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8888, function() {
console.log((new Date()) + ' Server is listening on port 8888');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept();
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF('Message received at server:'+message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
save the above file as .js and run it like node filename.js from terminal or command prompt
The above file is like we have first created a http server using node then we're passing the created http server instance to Websocketserver then subsequently to Socket.iO instance
I was debugging a similar issue and found that if you have used https to get the web page iOS will trap if you use the pass a the "ws:" protocol into WebSocket. If you use "wss:" everything will work and there will be no traps.