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

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?

Related

PeerJS error : Cannot receive messages

Hello I'm trying to use PeerJS to send and receive message datas, so take a look to my code:
var peer = new Peer({key: 'my-personnal-peer-id-key'});
peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});
var dest = prompt("id de destination à appeller")
var conn = peer.connect(dest);
conn.send('Hello!');
conn.on('open', function() {
console.log('2')
// Receive messages
conn.on('data', function(data) {
console.log('3')
console.log('Received: ' + data);
});
});
In the window.prompt, I paste the destination peer id, but I don't receive any message in the console log at the following line:
console.log('Received: ' + data);
Please help me.
The connection has to have an event listener for 'data' to handle the received data. From your code, it looks like conn.send() is called before conn.on('data') is executed.
This means when conn.send is executed, the connection has no data event listener and hence the sent data is not handled at all.
It could be done like this
var conn = peer.connect(dest);
conn.on('open', function() {
console.log('2')
// Receive messages
conn.on('data', function(data) {
console.log('3')
console.log('Received: ' + data);
});
conn.send('Hello!');
});

SOAP Request to Wemo switch from Pebble returns status 500

Been trying to write a pebble app for wemo switches, currently this is the code i'm using:
function WemoRequest(callback) {
if (SOAPData === false || SOAPData === undefined) {
console.log("Invalid SOAP data: " + JSON.stringify(SOAPData));
return;
}
var url = "http://192.168.1.230:49153/upnp/control/basicevent1";
try {
var request = new XMLHttpRequest();
request.open("POST", url, false);
request.setRequestHeader("SOAPAction", "urn:Belkin:service:basicevent:1#GetBinaryState");
request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status === 200 && callback) {
callback(request, SOAPData);
}else{console.log("Status: "+request.status + " State: "+request.readyState+" Callback: "+callback);}
};
var packet = '<?xml version="1.0" encoding="utf-8"?>'+
'<s:Envelope xmls:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+
'<s:Body>'+
'<u:GetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"></u:GetBinaryState>'+
'</s:Body>'+
'</s:Envelope>';
request.send(packet);
} catch (error) {
console.log("Error in XMLHttpRequest: " + error);
}}
I currently get status 500 from OnReadyStateChange and have no idea what I'm doing wrong. If this isn't enough code, app code is available here:https://github.com/dmf444/Webble
So...I know this is from 4 years ago lol, but I found this during a google search and just found the answer, so I figured I would respond for that reason: I think your header just needs an extra set of quotes around "urn:Belkin:service:basicevent:1#SetBinaryState" so that the string specifying the soapaction literally starts and ends with quotes.
I'm working in Python (because that's what all the kids seem to be doing these days), but I too was getting the 500 error until I made a very subtle change (the single quote marks around my double quotes) and almost cried tears of joy when my light turned off:
"SOAPACTION": '"urn:Belkin:service:basicevent:1#SetBinaryState"'
So here's the working version of the code (in Python lol):
import http.client
#Variables (value=on/off, ipaddress=address of your wemo)
value = 0 #1=ON, 0=OFF
ipAddress = "192.168.0.108"
#Build the SOAP Envelope (data)
data = '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"><BinaryState>' + str(value) + '</BinaryState></u:SetBinaryState></s:Body></s:Envelope>'
#Build the Header (headers)
headers = {"Content-type" : 'text/xml; charset="utf-8"', "SOAPACTION": '"urn:Belkin:service:basicevent:1#SetBinaryState"', "Content-Length": len(data)}
#Send request and check response data (resp_data)
conn = http.client.HTTPConnection(ipAddress, 49153)
conn.request("POST", "/upnp/control/basicevent1", data, headers)
response = conn.getresponse()
resp_data = response.read()
if response.status == 200:
conn.close()
print("SUCCESS!")
elif response.status == 403:
print("ERROR: 403 (FORBIDDEN)")
else:
print("ERROR: " + str(response.status))

Nodejs - websocket-node module: How to make multi-client socket-server works?

I created a socket server using websocket module with this configuration taken from this example (with some changes):
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(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
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('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(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.');
});
});
I create my own client in html :
<html>
<head>
<script src='./js/jquery1-11-3-min.js'></script>
<script>
$(document).ready(function (){
buildwebsocket();
});
var ws;
function buildwebsocket(){
ws = new WebSocket("ws://192.168.0.96:5050",'echo-protocol');
ws.onopen = function(evt) { onOpen(evt) };
ws.onclose = function(evt) { onClose(evt) };
ws.onmessage = function(evt) { onMessage(evt) };
ws.onerror = function(evt) { onError(evt) };
}
function onOpen(ev){
//alert("konek men! mantap! :D");
$("#recmsg").append("connected!<br>");
}
function onClose(ev){
$("#recmsg").append("connection closed!<br>");
}
function onMessage(ev){
//alert("ada pesan datang!");
$("#recmsg").append(ev.data+"<br>");
}
function onError(ev){
$("#recmsg").append("connecting error!<br>");
}
function doSend(){
//writeToScreen("SENT: " + message);
var message = $("#pesan").val();
ws.send(message);
} function doClose(){
ws.close();
}
//function writeToScreen(message){
//var pre = document.createElement("p");
//pre.style.wordWrap = "break-word";
//pre.innerHTML = message;
//output.appendChild(pre);
//}
//window.addEventListener("load", init, false);
</script>
</head>
<body>
<button onclick='doClose()'>Close</button>
<textarea id='pesan'></textarea><br>
<button onclick='doSend()'>Kirim!</button>
<br>
received message
<div id='recmsg'>
</div>
</body>
</html>
The connection between client (first client) and the server was successfully established. I try to send messages from first client, then the server receives the message without any promblem, and then the message sent back to the first client, and the first client receives it. I can say the connection and the socket works well.
I try to establish another connection (second client), so I open the second client in another device. The connection is good. But, when I send messages from the first or the second client, the first client doesn't get the response but the second client gets it.
And if open the third client and then send a message, the first and the second client don't get the response. Only the last connected client receives the response from server, and there's no client receives any error messages.
Is it the cons of the module? or the server configuration must be changed/added?
Can I establish multi-client-supported-socket-server using this module?
You're not storing the connections on the server side. You're just setting them up on the server to communicate directly back and forth to the server. If you want messages going to the server to be sent back out to everyone, you need to set up the .on('message', ...) function for each connection on the server to have that behavior. To do this, you'll need to store the connections as they are created. Try this:
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(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
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;
}
//create an array to hold your connections
var connections = [];
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('echo-protocol', request.origin);
//store the new connection in your array of connections
connections.push(connection);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//send the received message to all of the
//connections in the connection array
for(var i = 0; i < connections.length; i++) {
connections[i].sendUTF(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.');
});
});

ejabberd XMPP connection failed using strophejs

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.

creating a tcp socket with net.createConnection(port, [host]) in node.js

Anyone here can give me a few pointers working with sockets in node.js?
can open a tcp connection say on 172.0.0.1 on port 8000 for example using net.createConnection(port, host)
var net = require('net'),
querystring = require('querystring'),
http = require('http'),
port = 8383,
host = 172.123.321.213,
path = /path/toService,
_post = '';
var server = http.createServer(function(req, res) {
if(req.method == 'POST') {
req.on('data', function(data) {
body+=data;
});
req.on('end', function() {
_post = querystring.parse(body);//parser post data
console.log(_post);
})
}
var socket = net.createConnection(port, host);
var socket = net.createConnection(port, host);
socket.on('error', function(error) {
send404(res, host, port);
})
socket.on('connect', function(connect) {
console.log('connection established');
res.writeHead(200, {'content-type' : 'text/html'});
res.write('<h3>200 OK:
Connection to host ' + host + ' established. Pid = ' + process.pid + '</h3>\n');
res.end();
var body = '';
socket._writeQueue.push(_post);
socket.write(_post);
console.log(socket);
socket.on('end', function() {
console.log('socket closing...')
})
})
socket.setKeepAlive(enable=true, 1000);
}).listen(8000);
send404 = function(res, host, port) {
res.writeHead(404, {'content-type': 'text/html'});
res.write('<h3>404 Can not establish connection to host: ' + host + ' on port: ' + port + '</h3>\n');
res.end();
}
But now I need to send my data to the path defined - if I add the path to host then try connection then connection will fail.
Any ideas?
Thanks in advance
Your "socket" object is just a plain TCP socket which is just a simple bidirectional communication channel. The HTTP methods you're trying to use (e.g. res.writeHead()) don't pertain, so you'll have to write the request manually. Try something like this:
var socket = net.createConnection(port, host);
console.log('Socket created.');
socket.on('data', function(data) {
// Log the response from the HTTP server.
console.log('RESPONSE: ' + data);
}).on('connect', function() {
// Manually write an HTTP request.
socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
console.log('DONE');
});