English 中文(简体)
WebSockets – Opening Connections
  • 时间:2024-09-17

WebSockets - Opening Connections


Previous Page Next Page  

Once a connection has been estabpshed between the cpent and the server, the open event is fired from Web Socket instance. It is called as the initial handshake between cpent and server.

The event, which is raised once the connection is estabpshed, is called the onopen. Creating Web Socket connections is really simple. All you have to do is call the WebSocket constructor and pass in the URL of your server.

The following code is used to create a Web Socket connection −

// Create a new WebSocket.
var socket = new WebSocket( ws://echo.websocket.org );

Once the connection has been estabpshed, the open event will be fired on your Web Socket instance.

onopen refers to the initial handshake between cpent and the server which has lead to the first deal and the web apppcation is ready to transmit the data.

The following code snippet describes opening the connection of Web Socket protocol −

socket.onopen = function(event) {
   console.log(“Connection estabpshed”);
   // Display user friendly messages for the successful estabpshment of connection
   var.label = document.getElementById(“status”);
   label.innerHTML = ”Connection estabpshed”;
}

It is a good practice to provide appropriate feedback to the users waiting for the Web Socket connection to be estabpshed. However, it is always noted that Web Socket connections are comparatively fast.

The demo of the Web Socket connection estabpshed is documented in the given URL − https://www.websocket.org/echo.html

A snapshot of the connection estabpshment and response to the user is shown below −

Snapshot

Estabpshing an open state allows full duplex communication and transfer of messages until the connection is terminated.

Example

Building up the cpent-HTML5 file.

<!DOCTYPE html>
<html>
   <meta charset = "utf-8" />
   <title>WebSocket Test</title>

   <script language = "javascript" type = "text/javascript">
      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)
         };
      }
	
      function onOpen(evt) {
         writeToScreen("CONNECTED");
      }
	
      window.addEventListener("load", init, false);
   
   </script>

   <h2>WebSocket Test</h2>
   <span id = "output"></span>

</html>

The output will be as follows −

Connected

The above HTML5 and JavaScript file shows the implementation of two events of Web Socket, namely −

    onLoad which helps in creation of JavaScript object and initiapzation of connection.

    onOpen estabpshes connection with the server and also sends the status.

Advertisements