HTML5 – Web sockets
Web sockets are a full-duplex communication channel over a single TCP connection, which allows a web application to send and receive data in real-time. HTML5 introduced the WebSocket
interface, which allows web applications to create and communicate with web socket servers.
To use web sockets, you can use the WebSocket
constructor to create a new web socket object:
var socket = new WebSocket('ws://echo.websocket.org');
In this example, the WebSocket
constructor is used to create a new web socket object that connects to the echo server at ws://echo.websocket.org
.
To send data through the web socket, you can use the send
method of the web socket object:
socket.send('Hello server!');
In this example, the send
method is used to send a message to the server.
To receive data through the web socket, you can use the onmessage
event handler of the web socket object:
socket.onmessage = function(event) {
console.log(event.data); // Outputs 'Hello client!'
};
In this example, the onmessage
event handler is called when the server sends a message, and the event
object passed to the event handler has a data
property that contains the data of the message.
Here is an example of how to use web sockets to send and receive messages in real-time:
var socket = new WebSocket('ws://echo.websocket.org');
// Send a message to the server
socket.send('Hello server!');
// Receive a message from the server
socket.onmessage = function(event) {
console.log(event.data); // Outputs 'Hello client!'
};
// Send a message to the server every 2 seconds
setInterval(function() {
socket.send('Hello again, server!');
}, 2000);
In this example, the onmessage
event handler is called when the server sends a message, and the event
object passed to the event handler has a data
property that contains the data of the message. The setInterval
function is used to send a message to the server every 2 seconds.