Websockets Issue, Perhaps Same Origin Policy? - html

I have a site hosted at localhost:8000. Now, I have a server listening for websocket connections at localhost:8001. I would like my website to connect to this server through the websocket api like
var conn = new WebSocket('ws://localhost:8001');
But I get some errors in Chromium 6.0.472.62 upon calling
conn.send('something');
That looks like: Uncaught Error: INVALID_STATE_ERR: DOM Exception 11.
In Firefox 4 (4.0b8pre), I get the error:
An attempt was made to use an object that is not, or is no longer, usable" code: "11
I thought this was an issue with the handshake not supporting websocket draft76 on the server, but I am using http://github.com/miksago/node-websocket-server/tree/master/lib/ws/ which claims to support draft75 and draft76.
Also, the initial handshake seems to work fine. I can receive a response from the server upon creating the new WebSocket, however, the problems arise on the call to "send" from the client side.
Is this an issue with the same origin policy since my httpserver is on port 8000 and the websocket server is on 8001? If so, how can I work around this?

Perhaps you need to wait for the onopen event to fire?
var conn = new WebSocket('ws://localhost:8001');
conn.onopen = function (e) {
conn.send('something');
}
conn.onmessage = function (e) {
console.log('got something: ' + e.data);
}
Also, it's a good idea to hook the onclose and onerror events too.

Related

In Firefox/Chrome devtools Is there a way to send/edit websocket messages after connection

I have a Safari/Firefox/Chrome browser. My browser has devtools.
Is there a way to happy send/edit websocket messages for existing connection?
Or by plugin?
Thank you
You can grab instance of websocket connection and can use it further to send further messages on it.
Grab socket connection instance
You must be aware of websocket connection establishment as below:
websocket = new WebSocket('your-ws-url-goes-here');
Now you can use instance of websocket and can use .send() and .close().
Your question states that you want to use existing connected web socket, you can look for socket connection instance in source code and can use it for sending further messages.
Example to play with
You can play with websocket and its instance here at http://websocket.org/echo.html
Notice here
var wsUri = "wss://echo.websocket.org/";
and function having
websocket = new WebSocket(wsUri);
You so you know websocket is connected and having instance in websocket
You can open devtool and type websocket to see all of the option. So in your case you need to find instance of connection so you can play with it.
About editing existing message
I couldn't find if there is any way to edit sent messages, and i think it should not be there. You can send new message since earlier message must have been responded already.
You can list all WebSocket connections on page in Chrome by opening a console and writing queryObjects(WebSocket). It should list all instances after a while.
Then choose the one you want to use and right-click on it and choose "Store object as global variable".
This will create a new variable like temp1 so you can send messages with temp1.send({websocket: 'message'}).

Error sending data to a HTTPS server with as3httpclientlib

I'm trying to send some data from flash to a server. I was doing it with a test server and everything was ok. But when I change to test it into a real server it send me an error: " got Alert! Type=22" So I searched about it and I discover that its because the real server runs on HTTPS and the test runs on HTTP. So, reading the documentation of the as3httpclienlib library that I am using, I found that there is a bug with some HTTPS servers and cause some errors and don't leave flash send more than 40kb of data, so that throws the error Type 22 -> Record overflow
This only happens with TLS Sockets so I think that the solution is change the TLSSocket to a SSLSocket.
This is the code that I use to send the data to the server:
var client:HttpClient = new HttpClient();
var uri:URI = new URI("http://www.snee.com/xml/crud/posttest.cgi");
var variables:Array = [{name:"fname", value:"FirstName1"}, {name:"lname", value: "LastName1"}];
client.listener.onData = function(event:HttpDataEvent):void {
// Notified with response content in event.bytes as it streams in
};
client.listener.onComplete = function(event:HttpResponseEvent):void {
// Notified when complete (after status and data)
};
client.postFormData(uri, variables);
How can I change this sockets?
Does anyone have an example?
Is this the solution of the problem?

Multiple HTML5 Websockets - when one connection fails all remaining websocket connections are delayed

I have a project that uses multiple HTML5 websocket connections on the same page. When all connections are available, the page functions as expected. However, when one or more of the websocket connections are down, all remaining connections are blocked until the bad connection times out. After timeout, the remaining websockets connect as expected.
Note the uris array below. I have purposely added a bad websocket address to re-create this issue. When the each loop fires, the first uri connects immediately and updates a li tag in the html. The browser then hangs on the second (bad) uri for as long as 60 seconds before finally moving to the third uri which also connects immediately.
I was able to re-create this issue here: http://jsfiddle.net/eXZA6/2/
Javascript
var uris = {
'1': 'ws://echo.websocket.org/',
'2': 'ws://echo.websocket.org:1234/', //Bad websocket address
'3': 'ws://echo.websocket.org/'
};
var sockets = {};
$.each(uris, function(index, uri) {
sockets[index] = connect(index, uri);
});
function connect(index, uri) {
var websocket = new WebSocket(uri);
websocket.onopen = function (evt) {
$('li#' + index).text('Connected');
};
websocket.onclose = function (evt) {
$('li#' + index).text('Closed');
};
websocket.onmessage = function (evt) {
$('li#' + index).text('Received: ' + evt.data)
};
websocket.onerror = function (evt) {
$('li#' + index).text('Error');
};
return websocket;
}
HTML
<ul id="connection">
<li id="1" />
<li id="2" />
<li id="3" />
</ul>
I tried using setTimeout and other hacky multi-thread tricks with no luck.
Oddly enough, the functionality I expected appears to work in IE10, but not Firefox or Chrome.
Sounds like Firefox and Chrome are following the rules outlined in the WebSocket Spec RFC6455, and IE10 isn't.
Section 4.1: Client Requirements:
2. If the client already has a WebSocket connection to the remote
host (IP address) identified by /host/ and port /port/ pair, even
if the remote host is known by another name, the client MUST wait
until that connection has been established or for that connection
to have failed. There MUST be no more than one connection in a
CONNECTING state. If multiple connections to the same IP address
are attempted simultaneously, the client MUST serialize them so
that there is no more than one connection at a time running
through the following steps.
That essentially says that the behavior you are experiencing is the required behavior of a websocket client in order to be compliant with the spec.
Note the use of the word "MUST", an important and well defined key word in spec documents. This key word, along with others, are specifically called out in Section 2: Conformance Requirements.

HttpClient Portable returns 404 notfound on WP8

I'm porting a W8 application that uses httpclient library to connect to our server.
The main purpose of the application is to send images, but when I try to send pictures on my WP8 I got a 404 not found error (seems that Microsoft remapped to 404 a lot of errors), if i check the server logs, I can see that the server recevied about 1/4 of the image before failling. The same function seems to works fine in my W8 application (didn't tested on 3G), and works on WP8 if I use Wifi connection. I think that the problem could be the waiting time, so I tried to add Keep-Alive headers without success.
The current code I have is:
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMinutes(10);
Stream streamW = new MemoryStream();
this.bSyncOK = await Send(streamW);
streamW.Seek(0, SeekOrigin.Begin);
HttpResponseMessage response = await httpClient.PostAsync(sUri, new StreamContent(streamW));
if (response.IsSuccessStatusCode)
{
Stream streamR = await response.Content.ReadAsStreamAsync();
this.bSyncOK = await Recv(streamR);
streamR.Dispose();
}
else
throw new HostNotFoundException();
}
The same server is used to upload pictures on other platforms like IOS and Android without problems.
I reproduced the problem using fiddler to simulate modem speeds. The problem is happening because Phone's HTTPWebRequest implementation will timeout the request whenever it exceeds around 60s. In the debugger I see them getting back ERROR_INTERNET_TIMEOUT from their native layer. The only workaround I can think of at the moment would be to send the file in smaller POSTs, assuming the server supports that.

How to get HTTP status code in HTTPService fault handler

I am calling a server method through HTTPService from client side. The server is a RestFul web service and it might respond with one of many HTTP error codes (say, 400 for one error, 404 for another and 409 for yet another). I have been trying to find out the way to determine what was the exact error code sent by the server. I have walked teh entire object tree for the FaultEvent populated in my fault handler, but no where does it tell me the error code. Is this missing functionality in Flex?
My code looks like this:
The HTTP Service declaration:
<mx:HTTPService id="myServerCall" url="myService" method="GET"
resultFormat="e4x" result="myServerCallCallBack(event)" fault="faultHandler(event)">
<mx:request>
<action>myServerCall</action>
<docId>{m_sDocId}</docId>
</mx:request>
</mx:HTTPService>
My fault handler code is like so:
private function faultHandler(event : FaultEvent):void
{
Alert.show(event.statusCode.toString() + " / " + event.fault.message.toString());
}
I might be missing something here, but:
event.statusCode
gives me the status code of the HTTP response.
So I can successfully do something like this in my fault handler function:
public function handleFault(faultEvent:FaultEvent):void
{
if (faultEvent.statusCode == 401)
{
Alert.show("Your session is no longer valid.", "", Alert.OK, this, loginFunc);
}
else
{
Alert.show("Failed with error code: " + faultEvent.statusCode as String);
}
}
Looks like you are out of luck: http://fantastic.wordpress.com/2007/12/26/flex-is-not-friendly-to-rest/
You may have to use ExternalInterface to get this handled in JS and then communicated to Flex.
The Flash Player needs help from the browser to be able to access the HTTP status code; therefore, this is not available on all platforms. For me, it failed with Flash Player 10.3.183.11 and Firefox 3.6.26, but worked with IE 8 on Windows 7.
The Adobe help for the FaultEvent.statusCode property hints at this, but unfortunately doesn't go into details:
this property provides access to the HTTP response status code (if available), otherwise the value is 0
So, if you absolutely need the status code, bad luck; if it's just to generate a better or friendlier error message for some frequent error conditions, it may be sufficient.
as3httpclient as posted by Ross is friendly to Rest, and provides you with the HTTP status code, as long as you're developing for AIR and not a browser-based app.
I could not get as3httpclient to work from the browser, even when making requests to the same origin. There's documentation stating you need to set up a socket policy file server to get this to work. Not scalable for our uses so I setup a Proxy web service on the same host running the flex app.
I use HTTPService to make the call to the proxy web service, which forwards the request to the destination, and the proxy web service returns the http status code and message body back to the HTTPService in xml.
Try using this instead of HTTPService:
http://code.google.com/p/as3httpclient/