Connecting to HTML5 Websocket
I'm a bit confused about HTML5 Websockets. I've looked at numerous tutorials out there and a lot of them have different variations of connecting using different ports. What do these ports mean?
Adobe for instance, uses this:
new WebSocket('ws://localhost:1740');
Then another tutorial has this where no ports are required:
new WebSocket("ws://www.websockets.org");
And finally a third tutorial has a port, but it's completely different:
new WebSocket("ws://localhost:8080/echo");
My question would be, why do these vary? How do I know which ports to connect to? Also, I've attempted to do my own connection:
var ws = new WebSocket("ws://test.ontarget-network.com/");
But I get the following error: Unexpected response code: 200
I've tested around and tried connecting to various other "ports" (not knowing what I'm doing obviously, typing in random numbers) and this error would disappear, however, my code
ws.onopen = function(){
alert("Connection Established");
};
would not execute.
I'm trying to fully understand HTML5's Websockets API so I can experiment and create more dynamic applications. Thanks for the help.
The following comes from the latest WebSocket draft:
By default the WebSocket protocol uses port 80 for regular WebSocket connections and port 443 for WebSocket connections tunneled over TLS [RFC2818].
Really though, you should be able to use any valid port not in use. As long as clients are trying to connect to the same port that the server-side script opens for the socket connection, you should be fine.
A quick note on ports:
- Port 80 is the HTTP port.
- Port 8080 is the alternate HTTP port.
- Port 443 is the HTTPS (ie, HTTP with TLS) port.
- Port 1740 in the Adobe code seems like some random port not already in use by other services.
For a full list of preset ports, please see the following:
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
As for your "Unexpected response code: 200" error, I'm guessing that the WebSocket URL you're using on the client side is not pointing to a valid server-side script, but that's hard to comment on without more info.
The server should have an endpoint that accepts WebSocket connections. So, if that endpoint is /echo
you would want to connect to:
ws://localhost:8080/echo/websocket
You will get the Unexpected response code: 200
error if you exclude the /websocket
suffix after the endpoint. I was having the same confusion and this link cleared things up a bit for me.
I had the same issue, But to survive with
Unexpected response code: 200
You need to have either server-side script to handle the web socket, or you can use Node.js to build a you server script. for the sake of education you can try to biuld your own websocket sever script.
链接地址: http://www.djcxy.com/p/44700.html上一篇: WebSockets协议vs HTTP
下一篇: 连接到HTML5 Websocket