Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use Sockets in JavaScript\HTML? [closed]

How to Use Sockets in JavaScript\HTML?

May be using some cool HTML5?

Libraries? Tutorials? Blog Articles?

like image 613
Rella Avatar asked Nov 15 '09 02:11

Rella


People also ask

How do you close a Javascript WebSocket?

To close a WebSocket connection, you can simply use the WebSocket. close() method, for example, like so: const ws = new WebSocket('ws://localhost:8080'); // ... ws.

How do you call a Javascript socket?

socket= new WebSocket('ws://www.example.com:8000/somesocket'); socket. onopen= function() { socket. send('hello'); }; socket.

How do I disconnect a WebSocket?

close() The WebSocket. close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED , this method does nothing.

How do I connect a socket in HTML?

var Socket = new WebSocket(url, [protocal] ); Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.


1 Answers

How to Use Sockets in JavaScript/HTML?

There is no facility to use general-purpose sockets in JS or HTML. It would be a security disaster, for one.

There is WebSocket in HTML5. The client side is fairly 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 specialised socket application on the server-side to take the connections and do something with them; it is not something you would normally be doing from a web server's scripting interface. However it is a relatively simple protocol; my noddy Python SocketServer-based endpoint was only a couple of pages of code.

In any case, it doesn't really exist, yet. Neither the JavaScript-side spec nor the network transport spec are nailed down, and no browsers support it.

You can, however, use Flash where available to provide your script with a fallback until WebSocket is widely available. Gimite's web-socket-js is one free example of such. However you are subject to the same limitations as Flash Sockets then, namely that your server has to be able to spit out a cross-domain policy on request to the socket port, and you will often have difficulties with proxies/firewalls. (Flash sockets are made directly; for someone without direct public IP access who can only get out of the network through an HTTP proxy, they won't work.)

Unless you really need low-latency two-way communication, you are better off sticking with XMLHttpRequest for now.

like image 119
bobince Avatar answered Sep 24 '22 02:09

bobince