HTML5 Websocket TCP Port Listening - javascript

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.

Related

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.

I cannot send a message from my client using websocket to local server

I'm working on webstorm exactly a PhoneGap project and websocket and I cannot send a message from my client using websocket to local server. Thank you for your help.
<!--
Lincense: Public Domain
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample of web_socket.js</title>
<script src="js/websocket.js"></script>
<!-- Include these three JS files: -->
<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:9777");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("message");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
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>
I have been working on this problem for 2 days any help please!

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?

websocket unable to connect to android emulator

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.

Categories