Welcome Guest! (App Version 3.1)

websitnero logo name

Web Sockets

Using Web Sockets in HTML5

Websockets are nearly similar to SSE with the only difference that SSE is a one-way data sharing which the Websockets provide two way data sharing or sending, ie from server to client, but also from client to the server. So, websockets are very useful in providing real time updates and interactions to the end-user. Learning websockets is really fun and a good tool to implement.

Example

<div id="output"></div>

<script>

var wsUri = "ws://echo.websocket.org/";
var output;

function init() {
  output = document.getElementById("output");
  testWebSocket();
}

function testWebSocket() {
  websocket = new WebSocket(wsUri);
  websocket.onopen = function(evt) { onOpen(evt) };
  websocket.onclose = function(evt) { onClose(evt) };
  websocket.onmessage = function(evt) { onMessage(evt) };
  websocket.onerror = function(evt) { onError(evt) };
}

function onOpen(evt) {
  writeToScreen("CONNECTED");
  doSend("WebSocket rocks");
}

function onClose(evt) {
  writeToScreen("DISCONNECTED");
}

function onMessage(evt) {
  writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
  websocket.close();
}

function onError(evt) {
  writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}

function doSend(message) {
  writeToScreen("SENT: " + message);
  websocket.send(message);
}

function writeToScreen(message) {
  var pre = document.createElement("p");
  pre.style.wordWrap = "break-word";
  pre.innerHTML = message;
  output.appendChild(pre);
}

window.addEventListener("load", init, false);

</script>
WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.