websocket unable to connect to android emulator - javascript

So here's the code for my very simple WebSocket code to connect to the Android Emulator ... and it hangs.
I can confirm I can telnet to the emulator fine. I can also Websocket to a web server ok, even though http gives the old "unexpect response code 200". I can also confirm that the readState is a constant zero.
I can also confirm that a connection is established when the page is connected and disconnects when it's removed.
Whilst page up:
$ netstat -a | grep 5554
TCP 127.0.0.1:5554 eww:0 LISTENING
TCP 127.0.0.1:5554 eww:49516 ESTABLISHED
TCP 127.0.0.1:5554 eww:54424 ESTABLISHED
TCP 127.0.0.1:49516 eww:5554 ESTABLISHED
TCP 127.0.0.1:54424 eww:5554 ESTABLISHED
After page removed:
$ netstat -a | grep 5554
TCP 127.0.0.1:5554 eww:0 LISTENING
TCP 127.0.0.1:5554 eww:49516 ESTABLISHED
TCP 127.0.0.1:49516 eww:5554 ESTABLISHED
TCP 127.0.0.1:54424 eww:5554 TIME_WAIT
I'm using Chrome and this is all running on Windows 7. The other connection is likely to be Eclipse.
Any thoughts?
<!DOCTYPE html>
<html>
<head>
<title>Telnet to Android Emulator</title>
<style>
#messages {
list-style: none;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1>Telnet to Android Emulator</h1>
<ul id="messages">
</ul>
<script>
$(document).ready(function() {
function log(message) {
$('#messages').append('<li>' + message + '</li>');
}
var socket;
if ("WebSocket" in window) {
log("WebSocket API supported");
} else {
log("WebSocket API not supported");
}
function wsOpen(e) {
log("OPEN");
}
function wsClose(e) {
log("CLOSED");
}
function wsError(e) {
log("ERROR " + e.data);
}
function wsMessage(e) {
log(e.data);
}
function openSocket() {
var wsuri = "ws://localhost:5554";
log("connecting to " + wsuri);
try {
socket = new WebSocket(wsuri);
socket.onopen = wsOpen;
socket.onclose = wsClose;
socket.onerror = wsError;
socket.onmessage = wsMessage;
} catch (exception) {
log('Caught ' + exception);
}
}
function closeSocket() {
log("disconnecting");
socket.close();
}
openSocket(); // down here for testing
});
</script>
</body>
</html>

WebSocket is a protocol in its own right and the Android Emulator does not speak it. That's why it's not connecting or calling the onopen function.
Time for a new strategy

I solved the problem by writing a Java Applet which does a telnet connection then passed information from the web page through it. In this case, I used clicks on a Google Map to pass "geo fix" data.
https://github.com/stevemarvell/GoogleMapToAndroidEmulator
It's not perfect, but it's a start.

Related

HTML5 Websocket TCP Port Listening

I am integration a desktop application with my asp.net mvc app. Desktop application is publishing the data on port:10000 which i need to listen in browser. Below is the code:
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://127.0.0.1:10000");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
Run WebSocket
</div>
</body>
</html>
The issue I am facing is when desktop app publish the data on port, connection terminates and i am getting a message connection closed. any help?
Looking at your code i dont see anywhere where you close the conecction with ws, so i think its the server who closes the connection after sending you the message.

How to connect to a node server from a button press?

Can I connect to a nodejs server with socket.io from a button press? I got my page for example file:///home...site/index.html and a server running on my local machine for example localhost:8080. Can i connect to the server from my file with when i call a function, using xmlhttprequest or other means? How? Got links/tutorials?
I have a very simple socket.io example on GitHub: socketio-example
Update the index.html page in this example to look like this:
<!doctype html>
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket;
function makeConnection() {
socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('polo', function(data) {
addMessage(data.message);
});
alert('connected.');
}
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
function marco() {
socket.emit('marco');
}
</script>
</head>
<body>
<button onclick="makeConnection()">Connect</button>
<button onclick="marco()">Marco!</button>
<ul id='messages'></ul>
</body>
</html>
This will establish the socket.io connection when the user clicks Connect. Then you may click Marco! to send a message and receive the Polo! response.

Sending messages with Websockets

I have the following html/javascript code that uses websockets to communicate with a server. It seems like I can only send(message) only inside the onmessage() and onopen() functions. How can I send data outside of those functions ?
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:57252/");
ws.onopen = function () {
ws.send("Hi, from the client."); // this works
alert("Connection opened...");
};
ws.onmessage = function (event) {
alert("Message received..." + event.data);
};
ws.onclose = function () {
alert("Connection closed...");
};
ws.send("Hi, from the client."); // doesn't work
ws.send("Hi, from the client."); // doesn't work
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
You are probably experiencing a race condition where you try to perform a send command even though the socket may not have been opened yet. There's an important note on the MDN that describes this behavior:
As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful.
You, essentially, are calling the send method immediately after creating a WebSocket.
If you move that logic to a function and call that function when you know the connection has been open, you might be fine. For example, try moving the code into a timeout or another function that can be manually triggered after you know the socket connection has been established:
function sendMyMessages() {
ws.send("Hi, from the client.");
ws.send("Hi, from the client.");
}
<button onclick="sendMyMessages()">Test</button>
Because onopen is an asynchronous event.
It's similar to doing this:
var value;
$.ajax({
url: '/post/data',
success: function(response) {
value = response;
}
});
alert(value);
What do we get in the alert? undefined.
The websocket works in a similar manner, you cannot send until the connection has finished opening. It opens asynchronously. Therefore, anytime you try to use send, you must ensure that the connection is already open. Right now, you are trying to synchronously use those send calls, before the connection is actually open.
This is the html file of Sanic webserver websocket demo.
<!DOCTYPE html>
<html>
<head>
<title>WebSocket demo</title>
</head>
<body>
<script>
var ws = new WebSocket('ws://' + document.domain + ':' + location.port + '/feed'),
messages = document.createElement('ul');
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode('Received: ' + event.data);
message.appendChild(content);
messages.appendChild(message);
};
document.body.appendChild(messages);
window.setInterval(function() {
data = 'bye!'
ws.send(data);
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode('Sent: ' + data);
message.appendChild(content);
messages.appendChild(message);
}, 1000);
</script>
</body>

javascript websocket connect to QWebSocketServer failed

I'm using QWebSocketServer to provide communication with javascript websocket.
The code is very similar with EchoServer in Qt Examples.
javascript side code is listed as following:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:12345");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
ws.onerror = function(error){
console.log('Error detected: ' + JSON.stringify(error));
}
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
However, I get this error:
Error detected: {"path":{"length":0},"cancelBubble":false,"returnValue":true,"srcElement":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState":3,"url":"ws://localhost:12345/","URL":"ws://localhost:12345/"},"defaultPrevented":false,"timeStamp":1408698611478,"cancelable":false,"bubbles":false,"eventPhase":2,"currentTarget":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState":3,"url":"ws://localhost:12345/","URL":"ws://localhost:12345/"},"target":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState":3,"url":"ws://localhost:12345/","URL":"ws://localhost:12345/"},"type":"error"}
What does this error mean? And does it mean that we cannot use QWebSocketServer to support javascript websocket?

using a Websocket page from the local Machine

I'm working on an applicatioin that I want to use with websocket interaction. I've used a node.js and socket.io based server and simple chat page as a starter for my page. I'm making modifications and figuring out the interactions between the server and html page.
The person who wrote the basic chat page used inline javascript on the html page as the client side of the chat, so I've broken that out into its own javascript file, no big deal there.
The issue is that I want to use the html and associated javascript file from the local machine, to connect to the node.js server I'm creating on the web-server. His setup was accessing the html page on the web-server in the same folder as the server.js file that acted as the web-socket server.
I'm trying to figure out how to get the client side javascript file to start doing it's thing when the page is opened (i'm guessing an on load event is needed), and how to set it up to call to the webserver javascript file.
I'm going to post his code here, it's not mine, I just used his tutorial to make the chat.html and server.js. Basically copy and paste.
Any help or guidance is greatly appreciated as always.
-----------------chat.html--------------------------
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var URL = window.location.protocol + "//" + window.location.host;
console.log("Connecting to " + URL);
var socket = io.connect(URL);
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function() {
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function(username, data) {
$('#conversation').append('<b>' + username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updateusers', this updates the username list
socket.on('updateusers', function(data) {
$('#users').empty();
$.each(data, function(key, value) {
$('#users').append('<div>' + key + '</div>');
});
});
// on load of page
$(function() {
// when the client clicks SEND
$('#datasend').click(function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if (e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
</head>
<body>
<h1>WebSocket Chat</h1>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>USERS</b>
<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
</body>
</html>
---------------------server.js-----------------------------
var port = 5000;
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
console.log("Listening on port " + port);
server.listen(port);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/chat.html');
});
// usernames which are currently connected to the chat
var usernames = {};
io.sockets.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameter
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});

Categories