2.WebSocket Client in JavaScript - HeroLiu183/WebSocketLab GitHub Wiki

Abstract

In this document will show you how to write client JavaScript code, by go throw following topics

  • Check WebSocket is available on client
  • Init WebSocket connection
  • WebSocket callbacks
  • Send Message to Server

Check WebSocket is available on client

there are two ways check is webSocket support on browser

if ("WebSocket" in window) 
{
    alert("WebSocket is supported by your Browser!");
}

OR

if(window.WebSocket){
    alert("WebSocket is supported by your Browser!");
}

Init WebSocket connection

Create WebSocket instance and assign callbacks

  1. Create instance new WebSocket("_PROTOCOL_://_SERVER PATH_").
  • _PROTOCOL_ must be ws or wss
var ws = new WebSocket("ws://localhost:100/");
  1. Assign Callbacks: onopen, onmessage, onclose
ws.onopen = function () 
{
    alert("socket is opened!!");
};
ws.onmessage = function (evt) {
    var received_msg = evt.data;
    console.log(received_msg);
    alert("Message is received...");
    document.getElementById("receiveMsg").innerHTML = received_msg;
};
ws.onclose = function () {
    alert("Connection is closed...");
};

Life-cycle & Callbacks

  1. var ws = new WebSocket("ws://localhost:100/"); this code browser will handshake with server upgrade connection to WebSocket protocol and establish connection
  2. Callback onopen: will be executed after finish handshake and establish connection successful.
  3. Callback onmessage: will be executed after received message send by server on established connection.
  4. Callback onclose : will be executed after connection disconnect.

Close Connection

   ws.close();

Send Message to Server

To send message ws.send("_Message_");

   ws.send(document.getElementById("message").value);