I am trying to establish a websocket connection between my signalR server and an android app, built using the phonegap CLI.
The javascript code runs on browsers on my PC but when I package it for android it fails to connect and gives the following error: Error during negotiation request
Here is the javascript code -
<!DOCTYPE html>
<html>
<head>
<title>My New Application</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no;" />
<script type="text/javascript" src="js/jquery-1.7.1.js" ></script>
<script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="js/jquery.signalR-2.0.3.js"></script>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src=http://WEB_ADDRESS.net/signalrPush/signalr/hubs"></script>
<script type="text/javascript">
$(function() {
alert('Phonegap device ready event...');
/*
var connection = $.hubConnection("http://WEB_ADDRESS.net/signalrPush/signalr", { useDefaultPath: false });
connection.error(function (error){
alert("SignalR error: " + error);
});
var pushhubProxy = connection.createHubProxy('pushhub');
pushhubProxy.on('sendmsg',function(message){ $('#ulServerMessages').append('<li>' + message + '</li>'); alert(message);});
connection.start({ transport: ['webSockets', 'longPolling'] }).done(function(){ alert('Now connected, connection ID=' + connection.id);})
.fail(function(){ alert('Could not connect'); });
*/
$.connection.hub.url = "http://WEB_ADDRESS.net/signalrPush/signalr";
var mypushHub = $.connection.pushhub;
if(typeof(mypushHub)=="object")
{
alert(typeof(mypushHub));
mypushHub.client.sendmsg = function (message) {
$('#ulServerMessages').append('<li>' + message + '</li>');
alert(message);
}
$.connection.hub.start({jsonp: true}).done(function () {
mypushHub.server.broadcastmsg();
}).fail(function (error) { alert(error); });
}
else
{
alert(typeof(mypushHub));
alert("Connection Prob");
}
});
</script>
</head>
<body>
<div data-role="header">
<h1>Get Server Data</h1>
</div>
<div id="pusheddata" style="width:300px; height:400px; overflow: auto;">
<ul id="ulServerMessages"></ul>
</div>
</body>
</html>
The asp.net code is hosted on azure.
I also tried to connect without the generated proxy(commented code) which again worked on chrome but not on the android emulator(4.4).
Could someone tell me what I am doing wrong?
Thanks
I am having the same problem as you.
Websocket is a feature within html5 and is not supported by all browsers
Chrome browser supports websockets but android 4.4 (jelly beans) In-browser doesn't.
This is why Android developed kitkat (which supports the websocket).
If you want to use websocket within android 4.2,4.4 (jelly beans), you have to use websocket cordova plugin like the one here
there are alot of others and I am just like you trying to find an answer
Related
I began learning sockets today and I have some questions about how it works. I'm using flask_socketIO and this is the code I found in a tutorial
Main.py
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"
socketio = SocketIO(app, cors_allowed_origins="*")
#socketio.on("message")
def handleMessage(msg):
print("Message: " + msg)
send(msg, broadcast=True)
if __name__ == "__main__":
socketio.run(app)
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chat room</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.js"
integrity="sha512-/xb5+PNOA079FJkngKI2jvID5lyiqdHXaUUcfmzE0X0BdpkgzIWHC59LOG90a2jDcOyRsd1luOr24UCCAG8NNw=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(() => {
var socket = io.connect("http://127.0.0.1:5000");
socket.on("connect", () => {
socket.send("User has connected!");
});
socket.once("disconnect", () => {
socket.send("User has disconnected!");
console.log("User Disconnected");
});
socket.on("message", (msg) => {
$("#messages").append("<li>" + msg + "</li>");
console.log("Message recieved");
});
$("#sendButton").on("click", () => {
socket.send($("#myMessage").val());
$("#myMessage").val("");
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage" />
<button id="sendButton">Send</button>
</body>
</html>
I understand how message works but I don't understand how the connect and disconnect events work. When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to
$("#sendButton").on("click", () => {
socket.send($("#myMessage").val());
$("#myMessage").val("");
});
for the website. Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?
When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to
The browser sends it to the the server. The server prints it (in the server's terminal) and also sends it to all the connected browsers, which log it in #messages.
Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?
After the browser disconnects the browser tries to send the message to the server. The server never gets it because the browser already disconnected. Possibly the browser throws an exception when you try to send to a disconnected socket and so it never gets to the next line of code which calls console.log.
I'm trying to use cordova-plugin-file-opener2 to load a pdf in Cordova. I can't seem to get it to work in the browser or on Android.
Here is my app.js file:
(function () {
document.querySelector('#file-button').addEventListener('click', openFile);
function openFile(){
console.log('opening file');
console.log(cordova.file.applicationDirectory);
var fileName = 'www/assets/pdf/foo.pdf';
var pathToFile = cordova.file.applicationDirectory + fileName;
window.resolveLocalFileSystemURL(pathToFile, function (entry) {
cordova.plugins.fileOpener2.open(
entry.toInternalURL(),
'application/pdf', {
error: function (e) {
alert.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
alert.log('file opened successfully');
}
}
);
}, function (e) {
alert('File Not Found');
});
}
}());
And here's the html:
<!DOCTYPE html>
<html>
<head>
<script src="cordova.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<p><button id="file-button" class="help-btn">Help</button></p>
<div class='header'><h1>Directory</h1></div>
<div class='search-view'>
<input class='search-key' type="search" placeholder="Enter name"/>
<ul class='list employee-list'></ul>
</div>
<script src="lib/jquery.js"></script>
<script src="js/services/memory/EmployeeService.js"></script>
<script src="js/app.js"></script>
</body>
</html>
When the 'file-button' is clicked, it triggers the openFile function.
This shows me the following in the console:
adding proxy for Device cordova.js:1010:9
adding proxy for File cordova.js:1010:9
opening file app.js:6:9
"http://localhost:8000/" app.js:7:9
And the alert message says 'File not found'.
App.js is located in www --> js
foo.pdf is located in www --> assets --> pdf
I'm begginer in Node.js or websocket. I have problem:
My HTML code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
"use strict";
var gniazdo = new WebSocket('ws://localhost:3000');
gniazdo.onopen = function(){
console.log('Połączono');
};
gniazdo.onmessage = function(m){
console.log(m.data);
};
</script>
</body>
</html>
My Node.js code:
var io = require('socket.io')(3000);
io.on('connection', function(socket){
console.log('a user connected');
});
I have error in console:
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
Help plz :)
Your client is using WebSockets, but Socket.IO has its own protocol (that may be transported over WebSockets, but it can also be transported over other protocols). Change your client to use Socket.IO's own client:
<script src="https://cdn.socket.io/socket.io-1.1.0.js"></script>
<script>
'use strict';
var gniazdo = io('ws://localhost:3000');
gniazdo.on('connect', function () {
console.log('Połączono');
gniazdo.on('message', function (m) {
console.log(m.data);
});
});
</script>
I am trying to download an apk file on a button click using phonegap. Why does this code not work? Nothing happens when I click Download. Could someone point me in the right direction? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function foo()
{
var fileTransfer = new FileTransfer();
fileTransfer.download(
"http://samplewebsite.com/example.apk",
"file:///sdcard/example.apk",
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
</script>
</head>
<body>
<button onclick="foo()">Download</button>
</body>
</html>
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var filePath= "/sdcard/directory/file.extension";
fileTransfer.download(uri,filePath,
function(entry) {
//success
},
function(error) {
//failed
}
);
This worked for me
Your code works fine.
This seems stupid but have you tried to use alert() instead of console.log() in the callbacks?
If you are sure the callback code is not invoked try to run just the app created by the phonegap' create script and check that the device is ready before doing other tests.
just my 2c
I would like to use this code
window.parent.document.getElementById('message').value += "\r\n\r\n[img]"+response+"[/img]";
It works fine for pages coming from the same domain, but not for sites from another domain loaded in the iFrame. How can I do it?
You can implement window.postMessage to communicate accross iframes/windows across domains.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
// What browsers support the window.postMessage call now?
// IE8 does not allow postMessage across windows/tabs
// FF3+, IE8+, Chrome, Safari(5?), Opera10+
function SendMessage()
{
var win = document.getElementById("ifrmChild").contentWindow;
// http://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/
// http://stackoverflow.com/questions/16072902/dom-exception-12-for-window-postmessage
// Specify origin. Should be a domain or a wildcard "*"
if (win == null || !window['postMessage'])
alert("oh crap");
else
win.postMessage("hello", "*");
//alert("lol");
}
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if (false) {
message = 'You ("' + evt.origin + '") are not worthy';
}
else {
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
var ta = document.getElementById("taRecvMessage");
if (ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
//evt.source.postMessage("thanks, got it ;)", event.origin);
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body>
<iframe id="ifrmChild" src="child.htm" frameborder="0" width="500" height="200" ></iframe>
<br />
<input type="button" value="Test" onclick="SendMessage();" />
</body>
</html>
Child.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
/*
// Opera 9 supports document.postMessage()
// document is wrong
window.addEventListener("message", function (e) {
//document.getElementById("test").textContent = ;
alert(
e.domain + " said: " + e.data
);
}, false);
*/
// https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
// http://ejohn.org/blog/cross-window-messaging/
// http://benalman.com/projects/jquery-postmessage-plugin/
// http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html
// .data – A string holding the message passed from the other window.
// .domain (origin?) – The domain name of the window that sent the message.
// .uri – The full URI for the window that sent the message.
// .source – A reference to the window object of the window that sent the message.
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if(false)
{
message = 'You ("' + evt.origin + '") are not worthy';
}
else
{
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
//alert(evt.source.location.href)
var ta = document.getElementById("taRecvMessage");
if(ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
// http://javascript.info/tutorial/cross-window-messaging-with-postmessage
//evt.source.postMessage("thanks, got it", evt.origin);
evt.source.postMessage("thanks, got it", "*");
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body style="background-color: gray;">
<h1>Test</h1>
<textarea id="taRecvMessage" rows="20" cols="20" ></textarea>
</body>
</html>
You can if your browser have disabled security, for chrome it's
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security
Update: I'm surprised that people keep devoting it because they consider it harmful, so here I add some additional details for peoples who don't know basics of web security and still try to develop for it.
DON'T use this solution if
you are using chrome plugins or apps which are not trusted by you, or
you have opened other sites in the chrome, or
you have some malicious chrome processes
your site is using any external resources.
To make this solution completely safe, configure your firewall to block all connections except one to which you are making CORS connection.
Also, don't use this solution if your connection endpoint isn't trusted.
Take a look at easyXDM, it's an easy to use library that provides a unified API for several tricks used to enable cross domain messaging, ranging from postMessage to the FIM-trick as a last resort.
This is what is used by major services such as Twitter and Disqus.
Due to same origin policy restrictions this is not allowed.
As stated, this falls under same origin policy, but there are some tricks that allow limited communication with the iframe. Take a look at http://ajaxify.com/run/crossframe/
You can't. This is called the same origin policy, and prevents javascript accessing content across domains.