HTML Web Sockets

 HTML Web Sockets


HTML5 provides a Web Sockets API that allows web developers to create real-time, two-way communication between the client and the server. This allows web applications to provide a richer, more interactive user experience, as data can be transmitted and received instantly, without requiring a page refresh.


Here's an example of using Web Sockets to create a chat application


<input type="text" id="message">

<button onclick="sendMessage()">Send</button>


<ul id="messages"></ul>


<script>

var socket = new WebSocket("ws://localhost:8080");


socket.onopen = function(event) {

  console.log("Socket opened");

};


socket.onmessage = function(event) {

  var message = event.data;

  var li = document.createElement("li");

  li.innerHTML = message;

  document.getElementById("messages").appendChild(li);

};


function sendMessage() {

  var message = document.getElementById("message").value;

  socket.send(message);

}

</script>


In this example, a text input field and a button are created, along with a unordered list element with an id of "messages". When the button is clicked, the sendMessage() function is called, which retrieves the value of the text input field, and sends it to the server using the socket.send() method.


The socket.onopen event handler is called when the WebSocket connection is opened, and the socket.onmessage event handler is called whenever a message is received from the server. In this case, the message is added to the unordered list element, creating a simple chat application.


The Web Sockets API can also be used to send and receive binary data, as well as handle errors and close events.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...