WebSocket works on HTML file, but fails on hosted web page - javascript

I'm trying to use Websocket to remote-control a LG Smart TV (WebOS 4.0) by using JSTVRemote JavaScript library.
It means the LG SmartTV is a websocket server, and my browser is a websocket client. The browser sends commands to control the TV, TV does the job (e.g. Volume Down) and send a response back to the client.
This library uses WebSocket to communicate with TV:
ws = new WebSocket( "wss://192.168.xxx.xxx:3000" ) ;
ws.onopen = function() {
ws.onmessage = function( event ) {
console.log( event ) ;
alert('command successed!')
}
ws.onclose = function() {
logUpdate( "Connection closed." ) ;
}
}
ws.send(someCommand);
When I use it in a local HTML file (open it in browser with file://...), It works correctly. The onmessage event fires and returns the response from TV. Also, the TV does the job of command.
*Chrome, IE and Safari are OK
However, when I use it in a hosted web page (open the same HTML file with http://... or https://...), the onmessage event does not file and it reports an error with "WebSocket is already in CLOSING or CLOSED state.". Of course, the TV does not do the job of command.
*the connection establishing seems to succeed because the new WebSocket(), ws.onopen() and ws.send() are OK.
I have tried following web server, but they don't work.
Apache
IIS
Web Server of QNAP(a NAS Server)
Does anyone know the reason of it?

Related

How to I start with Web Sockets?

I want to create a basic chat application using web socket in JavaScript. I searched a lot about it on various search engines but I didn't found anything that could help me.
I am using Wamp server and don't have NODE.js installed.
Can I create an application on Wamp?
How to write a server code for Web Sockets?
Note: I am aware of Client code for web socket but don't from where to start with server code?
The code I need can be in PHP or JavaScript.
Below is a basic client code written by Me.
<!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:9998/echo");
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>
If you are looking into a basic chat application you do not need web sockets, an AJAX polling will suffice.
The problem with PHP web sockets is that to use them you will need to create your own PHP server that will open a socket and listen on it. To do so you need to be able to run PHP scripts as CLI - you will need to have shell access on your server, which is not available on most shared hosting providers.
sailsjs is a great way to get started building a real-time web application using WebSockets. Sails uses express and socket.io to enable WebSockets functionality.
See this SailsCast to get started: Building a Sails Application: Ep21 - Integrating socket.io and Sails With Custom Controller Actions Using Real Time Model Events.

Java Script Web Socket client is not working

I'm developing php webpage And I want to use web socket.I developed a javascript web socket client.And I developed a websocket using java.Locally web socket client is working well.But when hosted, it is not working.My wen Socket is working well.When web page run locally,I use hosted java web socket and It is working well.
this is my javacript web socket client
var INIT_WS = "ws://184.72.171.96:9059/";
function openwebsocket(uname){
if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
writeResponse("WebSocket is already opened.");
return;
}
webSocket = new WebSocket(INIT_WS + "Sl2World/slworldendpoint/"+uname);
webSocket.onopen = function(event){
if(event.data === undefined)
return;
writeResponse(event.data);
};
webSocket.onmessage = function(event){
writeResponse(event.data);
};
webSocket.onclose = function(event){
writeResponse("Connection closed");
};
}
When php web page hosted,Why it is not working.In that case I can't get any error message.I thing web socket connection request is not going to java web socket.
thank you.
This would appear to be a security configuration issue on the host. While your local PHP file connects without a problem this will be because of a network firewall issue on your hosts network which would not affect a PHP file running on the same network. Most web hosts will not support websockets at this point due to their environments not being designed for them yet. Your best bet would be to find a host which specifically allows websockets and then ask them what socket numbers are allowed, or set up your own virtual or dedicated machine to run your java application.

Can socket.io work across domains?

I have a socket.io implementation, and I'm trying to make it work across domains but it appears it can't. Here's my exact use case:
I have a node.js server running socket.io.
I have a JS / HTML5 game that I want to be able to host from anywhere, which has the client socket.io code and tries to connect to the server.
I have the same JS code running on mobile devices via SpiderMonkey (this is one of the main reasons I need to run this from any domain).
I find that I simply cannot connect to the socket unless I am serving the JS code from my node.js server to a browser. If I simply open the HTML file on my disk from my browser, for example, it will not work.
Server code:
io.on( "connection", function( socket )
{
this.socket = socket;
this.socket.on( "echo", function( str ){ this.socket.emit( "message", str ); }.bind( this ) );
}.bind( this ) );
Client code:
this.socket = io.connect( ip );
this.socket.on("message", function( str ) { console.log( str ); } );
And I can't even connect, I get my print out that it's trying to connect, but it never succeeds and then starts throwing ping errors. So, is this even possible? Or must I do it with long polling or something?
The error:
[Error] Failed to load resource: A server with the specified hostname could not be found. (socket.io, line 0)
EXTRA INFO:
This specifically will not work if I am trying to connect from an HTML file opened from disk using file:///. I am going to try across different machines on the same network...
Yes, Socket.IO works cross-domain just fine. The actual Socket.IO library can/should be loaded from the server hosting it.
EXTRA INFO: This specifically will not work if I am trying to connect from an HTML file opened from disk using file:///.
Don't do that. You run into all sorts of weird issues when loading files off disk vs. over HTTP.
Failed to load resource: A server with the specified hostname could not be found.
This usually implies that whatever hostname you're trying to connect to isn't resolvable, indicating a DNS problem or that you typoed your hostname. In any case, your code example doesn't show the relevant part where the problem may be. Use your browser's developer tools to first determine that everything is loading correctly. Then, verify the address of what you're trying to connect to.

How to use Websocket for Firefox Android Addon

I am trying to write a simple firefox mobile addon that talks with my server side code using Websocket.
I have my code working for Desktop Firefox Addon but I am having difficulty with one for Firefox mobile.
function connectToServer(aWindow) {
var ws = new MozWebSocket("ws://ipaddress:8887"); // LINE 20
// var ws = new WebSocket("ws://ipaddress:8887");
ws.onopen = function() {
showToastMsg(aWindow, 'Sending');
ws.send('data');
}
ws.onmessage = function (evt) {
showToastMsg(aWindow, 'Display')
};
ws.onclose = function() {
};
I have tried both MozWebSocket and WebSocket, but both of them gives me error similar to the following :
E/GeckoConsole(15569): [JavaScript Error: "ReferenceError: MozWebSocket is not defined" {file: "resource://gre/modules/XPIProvider.jsm -> jar:file:///data/data/org.mozilla.firefox/files/mozilla/sq4c77hi.default/extensions/view-source#mydomain.org.xpi!/bootstrap.js" line: 20}]
Anyone know what I need to import or do to be able to reference WebSocket?
I just want to send data back and forth from my Firefox Android addon with my server side code using websocket. Any suggestions?
I am just confused because I have this setup running on Firefox Desktop Addon with very similar code.
Any help would be very appreciated thank you!
Try next solution
var ws = new Services.appShell.hiddenDOMWindow.WebSocket("ws://ipaddress:8887");
Are you using the Add-on SDK? Which file is this code going into?
First off, Mozilla 'un-prefixed' MozWebsocket to Websocket some time ago:
https://www.evernote.com/shard/s1/sh/59230d89-52f6-4f23-81de-75ab88f38c22/f9f1c0c64959ee44bdc833707efe10a9
...however the Websocket api is only available in actually web documents. What I've doen in the past is I've used the page-worker api to load a document in the background and connect to a Websocket server from the worker page:
https://github.com/canuckistani/Jetpack-Websocket-Example
For more in the page-worker api:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/page-worker.html
In the future we have plans to expose HTML5 apis more directly to add-on developers.

.Net WebSocket Prototype...Trouble Opening Connection in Javascript

Hi I have a Web Application and a Console Application in my C# .Net solution. I am trying to call a ReverseService class in my Console Application from my Web Application. In the Console Application in the static void Main function I am running the following code:
var host = new WebSocketsHost<ReverseService>(new Uri("ws://localhost:4502/reverse"));
host.AddWebSocketsEndpoint();
host.Open();
Console.ReadLine();
I am trying to call this WebSocketEndpoint from my Web Application with the following Javascript code in Chrome 12.
if (window.WebSocket) {
//establishes websocket connection
websocket = new WebSocket('ws://localhost:4502/reverse');
websocket.onopen = function () {
$('body').append('Connected.');
$('#inputbox').keyup(function () {
websocket.send($('#inputbox').val());
});
};
websocket.onclose = function () {
$('body').append('Closed.');
}
websocket.onmessage = function (event) {
$('#outputbox').val(event.data);
};
}
The websocket.onclose function does in fact get called, but the websocket.onopen function never does. I've googled and looked on here but to no avail, any help would be greatly appreciated.
The error is almost certainly a mismatch between the protocol versions for your client and server. It looks like you are using the HTML5 labs prototype - if you are using the most recent version then your server is talking WebSockets hybi-09. Chrome implements a much older version of the protocol (I think its hixie-76 but I am not certain).
Your options are:
Use a WebSocket server that implements hixie-76
Use a different client implementation. For example, you could use the implementation that is provided with the HTML5 labs prototype. Its a Silverlight plugin with a JavaScript wrapper. You need to include a few scripts and use new WebSocketDraft instead of new WebSocket. You will also need to drop the clientaccesspolicy.xml file in your wwwroot - see the prototype readme file for more info. Have a look at some of the samples for more info.
Use a TCP packet sniffer to watch the protocol handshake.
Successful tests with two protocols :
hybi-00/hixie-76 : Firefox 5.0, Safari 5.1.1 use this old protocol with Sec-WebSocket-Key1/Key2...
There are several free server source codes in C#.
For example search WebSocket76English.zip. It works even with Safari on iPhone.
hybi-06 : Firefox 7.0, Chrome 14 are using the last protocol with Sec-WebSocket-Key.
The last .Net WebSocket prototype use that protocol.
If someone has a version of WebSocket prototype supporting the old protocol hybi-00, please let me know.
The last specification draft suggest that a server can support several protocols and tell about
the supported versions in field Sec-WebSocket-Version.

Categories

Resources