How to use sockets in JavaScript \ HTML?

How to use sockets in JavaScript \ HTML?

Maybe you're using some cool HTML5?

Libraries? Textbooks? Blog Articles?

+82
javascript html html5 websocket
Nov 15 '09 at 2:39
source share
3 answers

Specifications:

Articles:

Textbook:

Libraries:

+55
Nov 15 '09 at 2:48
source share
— -

How to use sockets in JavaScript / HTML?

There is no way to use universal sockets in JS or HTML. That would be a safety disaster for one.

HTML5 has a WebSocket. The client side is pretty trivial:

socket= new WebSocket('ws://www.example.com:8000/somesocket'); socket.onopen= function() { socket.send('hello'); }; socket.onmessage= function(s) { alert('got reply '+s); }; 

You will need a dedicated server-side socket application to make connections and do something with them; this is not what you usually do with the web server scripting interface. However, this is a relatively simple protocol ; my noddy Python SocketServer endpoint was just a few pages of code.

In any case, it does not exist yet. Neither the specification on the JavaScript side nor the specification for network transport is nailed, and browsers do not support it.

However, you can use Flash, where available, to provide a script backup until WebSocket is widely available. Gimite web-socket-js is one such example. However, you are subject to the same restrictions as Flash Sockets, namely, that your server must be able to set cross-domain policies on request on the socket port, and often there are problems with proxy servers / firewalls. (Flash sockets are created directly, for someone who does not have direct public access to an IP address that can only get out of the network through an HTTP proxy, they will not work.)

If you really need low latency bidirectional communication, you'd better not embed XMLHttpRequest now.

+75
Nov 15 '09 at 3:01
source share

I think it's important to mention, now that this question is older than 1 year old, Socket.IO has since come out and seems to be the main way to work with sockets in the browser; as much as possible, it is also compatible with Node.js.

+46
Feb 25 '11 at 18:08
source share



All Articles