EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

What is WebSocket?

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Software Development Basics » What is WebSocket?

What-is-WebSocket

What is WebSocket?

Picture yourself writing an email to a friend or a colleague. You always start with Hi <friend>, followed by the context and end with a Thanks <name>. Now imagine the same you and your friend/colleague having a face to face conversation. Would you still start each of your text with Hi and end with Thanks? A big NO, right? That practically sums up HTTP and WebSocket.

Technical understanding

It is a two-way communication protocol. It provides a full-duplex connection. Let us understand how these terms are significant.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Looking back at our example of emails and face to face conversations, emails signify HTTP protocol while face to face conversations signify WebSocket protocol. This doesn’t mean that emails are sent over HTTP protocol, no. Emails mostly use SMTP protocols, but let’s not worry about that for now. The essential takeaway from the example is the opening and closing of the underlying connection between the two parties exchanging information.

HTTP exchanges information by opening a new connection on every request-response cycle. So every time you send a request or receive a response, HTTP establishes a new connection. Think of a connection as simply a secure line to transfer information. As soon as your information is delivered, HTTP closes the connection.

It keeps the connection open for you so that you can exchange information over the same line until one of you closes the connection.

A little more technical

Okay, I get it all about the connection being left open. How does it help me? I feel no difference whether I am sending emails or sending chat messages.

Popular Course in this category
JWS Java Web Services Training (4 Courses, 11 Projects)4 Online Courses | 11 Hands-on Projects | 65+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (4,636 ratings)
Course Price

View Course

Related Courses
Software Testing Training (9 Courses, 2 Projects)Selenium Automation Testing Training (9 Courses, 4+ Projects, 4 Quizzes)Appium Training (2 Courses)JMeter Testing Training (3 Courses)

You are right. As an end-user, the difference is not visible to you. Let’s think like an application developer. When I say open a secure line for information exchange, there is a process involved in it. This is commonly referred to as Handshaking. This is a process by which both the machines involved in a conversation agree to open a port to send and receive information. Now, these ports are blocked from one another and cannot be used for a third machine.

For handshaking, HTTP protocol sends and receives some extra bytes just to confirm whether a port is free in both the machines and fetches the details of the port. These extra bytes are an overhead when the frequent exchange of information is required. Hence, WebSocket.

When to use WebSocket and when not to?

By far, it is evident that it is useful only when the frequent exchange of information is required. It provides a duplex connection. This means that information can be sent and received at the same time. This obviously comes at the cost of blocking the port until the time information is exchanged. So, using WebSocket is a trade-off between saving crucial bytes and enabling faster conversations at the cost of blocking a port for longer.

The best use-case of WebSocket is when you need real-time data really quick, like stock prices. Stock prices change every second. So, using HTTP would waste crucial time in unnecessary handshaking, and the quotes would get stale. Instead, use this and get it done quicker.

Contrarily, if you can afford a delay of a few milliseconds in the information you seek, you must go for HTTP.

How WebSocket came into being?

In its initial days, the Internet was a giant network of pages containing textual information. These were mostly static pages, which meant that information was constant and did not vary with subsequent retrievals. Over time, rich content such as images became an indispensable part of the web pages. The pages also became dynamic, which meant that now the information on the pages could be generated based on queries.

This led to the advancement in technologies with the invent of Dynamic HTML, JavaScript, etc. They all were very advanced but used HTTP protocols. The problem with HTTP protocols – the connection was not duplex. The communication was unidirectional. At any point in time, either the client can send a request to the server or respond.

This gave way for WebSocket protocols allowing a full-duplex connection to enhance the user experience.

Understanding the term ‘Full-Duplex.’

We have been coming across the term full-duplex quite a lot. What does this actually mean?

In HTTP, the request is always initiated by the client. This means that unless the client sends a request, the server will not respond. This makes communication unidirectional.

While in WebSocket, both the client and server can push messages to each other at the same time. The client need not make a request each time it requires some response. This makes the connection bi-directional.

Now to achieve bi-directionality, one must think that there are two connections maintained at every point in time. This is where WebSocket is different. It does this over a single TCP connection. This is termed as a full-duplex connection, meaning two-way communication over a single channel.

Full Duplex

WebSocket Attributes, Events, and Methods

Let us create a WebSocket connection. The following command does this for us:

var Socket = new WebSocket(URL, [protocal] );

The new WebSocket method is the exposed API method that returns an established connection with the URL specified as the first parameter and adhering to an optional protocol parameter.

1. Attributes

Once the connection is established, we have the following attributes in our Socket object:

i. Socket.readyState

A read-only attribute that tells the state of the connection.
0 – Connection has not yet been established.
1 – Connection is established, and communication is possible.
2 – Connection is going through a handshake.
3 – Connection has been closed or could not be opened.

ii. Socket.bufferedAmount

A read-only attribute that tells the number of bytes that are queued using send() method.

2. Events

i. Socket.onOpen

An event triggered when a connection is opened.

ii. Socket.onMessage

An event triggered when the client receives a message from the server.

iii. Socket.onError

The event triggered an error in communication.

iv. Socket.onClose

The event triggered when a connection is closed.

3. Methods

i. Socket.send(data)

The send method transmits the data using the connection.

ii. Socket.close()

This method terminates the existing connection.

Example:

var socket = new WebSocket(“ ws://echo.websocket.org ”);
if (socket.readyState === WebSocket.OPEN){
socket.send(“Hello World”);
}
if (socket.readyState === WebSocket.OPEN){
socket.close( );
}

Real-World Example

StackOverflow is a very popular website that uses WebSocket to push notifications whenever a new answer is available to the question.

Real World Example

Recommended Articles

This has been a guide to What is WebSocket? Here we discussed the basic concepts, attributes, events, along with a real-world example of WebSocket. You can also go through our other suggested articles to learn more –

  1. Is Hadoop Open Source?
  2. What is Java Inheritance?
  3. What is Multithreading in C#?
  4. What is ASP.Net Web Services?

JWS Java Web Services Training (4 Courses, 11 Projects)

4 Online Courses

11 Hands-on Projects

65+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

2 Shares
Share
Tweet
Share
Primary Sidebar
Software Development Basics
  • Basics
    • Types of Algorithms
    • Vue.js?nextTick
    • Vue.js Transition
    • Page Replacement Algorithms
    • What is CLI
    • Open Source Software
    • Solve Problems With Technology (Simple)
    • What is Application Software & Types
    • System Software Tools
    • Typography App
    • Software as a Service (Saas)
    • Icon Font Pack
    • Interpret Results Using ANOVA Test
    • Blogging Insights Your Analytics
    • Increase Productivity Technology
    • Free Multimedia Software
    • Information Technology Benefits
    • What is SPSS and How Does It Work
    • Learn to Code For Beginners (Advance)
    • Uses of Coding
    • Uses Of Raspberry Pi
    • What Is System Design
    • Introduction to NLP
    • What is MapReduce
    • What is SoapUI
    • What is MVC
    • What is Multithreading
    • What is Elasticsearch
    • What is Neural Networks
    • What is Swift
    • What is PLC
    • What is Open Cart
    • What is XML
    • What is Mainframe
    • What is JMS
    • What is Cognos
    • What is Open Source
    • What is Bot
    • What is SOAP
    • What is COBOL
    • What is GraphQL
    • What is Microcontroller
    • What is Open-Source License
    • What is Visual Studio Code
    • What is Pandas
    • What is Hypervisor
    • What is Common Gateway Interface
    • What is IDE?
    • What is SSRS?
    • What is MVC Design Pattern
    • What is Application Server
    • What is GPS
    • What is NumPy
    • What is NLP
    • What is Botnet
    • What is Assembly Language
    • System Analysis And Design
    • HTTP Caching
    • What is Buffer Overflow
    • What is Ajax
    • What is Joomla
    • What is Appium
    • What is SVN
    • What is SPSS
    • What is WCF
    • What is Groovy
    • What is Clickbait
    • What is SOA
    • What is GUI
    • What is FreeBSD
    • What is WebSocket
    • What is WordPress
    • What is OSPF
    • What is Coding
    • CentOS Commands
    • What is Raspberry Pi
    • HTTP Cookies
    • What is Hub?
    • What is Bridge
    • What is Switch
    • What is Internet Application
    • What is Sensors
    • What is Proximity Sensors
    • What is Full Stack
    • System Design Interview Questions
    • What is Salesforce technology
    • What is Salesforce Sales Cloud
    • What is OOP
    • What is CMD
    • What is React
    • What is DSS
    • What is SVG
    • What is Apex
    • What is Desktop Software
    • Tor Browser, Anonymity and Other Browsers
    • Avoid Pitfalls of Shadow IT
    • Freelance Web Graphic Designer
    • What is Storage Virtualization
    • What is Web Services?
    • What is Social Networking?
    • What is Microservices Architecture?
    • Microservices Tools
    • Advantages of Microservices
    • Uses of Internet
    • Software Platforms
    • Uses of Internet for Business
    • Architecture of Web Services
    • Web Application Testing
    • Advantages of Web Service
    • CPU Virtualization
    • Types of Web Services
    • Web Services Testing
    • What is RabbitMQ?
    • RabbitMQ Architecture
    • Advantages of Bitcoin
    • Penetration Testing Services
    • Puppet Alternatives
    • What is Memcached?
    • What is Browser?
    • Types of Satellites
    • Model Driven Architecture
    • Types of Variables in Statistics
    • Integration Architecture
    • What is API Integration?
    • What is Grid Computing?
    • Asus File Manager
    • What is GPRS?
    • What is Gradle?
    • What is Basecamp?
    • Software System Architecture
    • GSM Architecture
    • What is Nagios?
    • AppDynamics Tool
    • Logical Architecture
    • What is Microsoft Planner
    • What is Circuit Switching
    • What is ARM?
    • Embedded Control Systems
    • Types of Embedded Systems
    • What is Bitbucket?
    • Requirement Engineering
    • What is WAP
    • What is Registry?
    • What is Dynatrace?
    • What is Digital Forensics?
    • Hardware Virtualization
    • AppDynamics Careers
    • Bandwidth Monitoring Tools
    • Ping Monitor Tools
    • Dynatrace Tools
    • What is Trello?
    • What is AppDynamics?
    • What is Remote Desktop?
    • What is Extranet?
    • What is LTE Network?
    • What is Firebase?
    • Website Monitoring Tool
    • Number Systems
    • Service Desk Manager
    • Static Website
    • Dynamic Website
    • What is Email?
    • What is URL Link?
    • What is Program?
    • What is Lock Screen?
    • What is Grafana
    • Unguided Media Transmission
    • IT Governance
    • IT Governance Framework
    • Remote Support Softwares
    • What is Unification?
    • Topological Map
    • What is LAMP?
    • USB Flash Drive
    • Software Development Models
    • Digital Circuit
    • What is Webpack?
    • Fault Tolerance
    • What is DSL Modem?
    • What is Mozilla Firefox?
    • What is Vagrant?
    • Types of Research Methodology
    • Grafana Plugins
    • Ionic Components

Related Courses

Software Testing Training

Selenium Training Certification

Appium Training

JMeter Certification Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - JWS Java Web Services Training (4 Courses, 11 Projects) Learn More