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.
bobince Nov 15 '09 at 3:01 2009-11-15 03:01
source share