EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Redis Tutorial Redis WebSocket
Secondary Sidebar
Redis Tutorial
  • Redis
    • Redis Pubsub
    • Redis GUI
    • Redis Database
    • Redis Get All Keys
    • Redis TTL
    • Redis EXPIRE
    • Redis Version
    • Redis EXPIRE
    • Redis List
    • Redis CLI Commands
    • Redis HSET
    • Redis FLUSHDB
    • Redis Key
    • Redis Persistence
    • Redis FLUSHALL
    • Redis pipeline
    • Redis SADD
    • Redis ZADD
    • Redis ZSET
    • Redis Get
    • Redis Replication
    • Redis Delete All Keys
    • Redis Use Cases
    • Redis HMSET
    • Redis Transactions
    • Redis Monitor
    • Redis HGET
    • Redis SETEX
    • Redis Rails
    • RedisJSON
    • Redis Get Key
    • Redis Auth
    • Redis gem
    • Redis Key Count
    • RedisTimeSeries
    • Redis Timeout
    • Redis LPUSH
    • Redis Architecture
    • Redis API
    • Redis Message Queue
    • Redis RPUSH
    • Redis Protocol
    • Redis Data Types
    • Redis Namespace
    • Redis ZRANGE
    • Redis Master Slave
    • Redis Memory Usage
    • Redis WATCH
    • Redis URL
    • Redis Key Value
    • Redis INCR
    • Redis EXISTS
    • Redis INFO
    • Redis HMGET
    • Redis Operator
    • Redis NOAUTH Authentication Required
    • Redis LRANGE
    • Redis RDB
    • Redis TLS
    • Redis HDEL
    • Redis WebSocket
    • Redis HGETALL
    • Redis GETSET
    • Node-RED WebSocket

Redis WebSocket

Introduction to Redis WebSocket

Redis websocket protocol offers a unidirectional and bi-directional channel of communication which makes real-time chat applications suitable. The connected users send messages to the application and exchange messages with each other for the setting of peer-to-peer. At the time of connecting redis server websocket connection are created within the associated application instance. The specified websocket enables the broadcast of messages between the users.

Redis WebSocket

Key Takeaways

  • Websocket in redis allows bidirectional and unidirectional communication from client to server. Also, it will allow connection from server to client.
  • Every web socket in Redis is identified by a URL that includes the ws prefix; we use different locators in WebSockets.

What is Redis WebSocket?

We are using publisher and subscriber for creating websocket in redis. The idea behind the publisher and subscriber is simple. The subscriber is a client which was listening to the changes from a set of data. The client who edits the data set is known as the publisher. When data is edited by publishers, it is heard by all subscribers who have subscribed to the publisher.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

We are creating real-time notifications by using websocket. Nowadays it is common to get real-time notifications while navigating web applications. Notifications can come from the chatbot or an alerting system. It defines the notification service at the time of developing a real-time notification application.

Why do we Use Redis WebSocket?

Basically, websocket in redis allows bidirectional communication. In redis, different users are associated with different instances. As a result, they are not able to exchange messages with each other so at the same time we need to use the redis websocket. Redis is nothing but a versatile key that can support multiple data structures. Redis includes the feature of publisher and subscriber capability in that publisher sends the message to the redis channel and the subscriber listens to the messages from this channel.

The redis publisher and subscriber are independent of each other, this is used to solve the problem. The redis publisher and subscriber are independent of each other, this is used to solve the problem. The message is sending the websocket connection is piped by using the redis channel for ensuring that the application is receiving the same. Websocket is basically used to communicate to the redis server, the communication is bidirectional also it is a full duplex between sender and receiver.

How to Create Redis WebSocket?

We are using different uniform locators for distinguishing the channels of unrelated communications.

1. Client Side

Client subscriber for different channel is notified when the specified event occurs. Events are classified into four types: user, group, session, and broadcast notification. The client declares the initialization on the channel that publishes the messages. In general, later is not important for websocket implementation. In the following example, we achieve the same result by applying the XML http request method.

Code:

var web_socket = new WebSocket('web_socket://www.test.com/web_socket/ws?');
web_socket.onopen = function() {
console.log("WS connected"); };
web_socket.onmessage = function(e) {
console.log("Msg received: " + e.data);
};
web_socket.onerror = function(e) {
console.error (e); };
web_socket.onclose = function(e) {
console.log("con closed"); }
function send_message (msg) {
ws.send (msg); }

Output:

Redis WebSocket request method

2. Client Javascript which depends on jQuery

At the time of using jquery clients are reconnecting to the websocket. We are accessing websocket as follows.

Code:

jQuery(document).ready(function($) {
var ws = WS4Redis({
uri: '{{ WEBSOCKET_URI }}',
connecting: on_connecting,
connected: on_connected,
receive_message: receiveMessage,
disconnected: on_disconnected,
heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
});
function sendMessage() {
ws.send_message('msg');
}
function on_connecting() {
alert ('WS connecting');
}
function on_connected() {
ws.send_message('Connect');
}
function on_disconnected(evt) {
alert('disconnected: ' + JSON.stringify(evt));
}
function receiveMessage(msg) {
alert('Msg from WS: ' + msg);
}
});

Output:

Accessing Redis WebSocket

3. Server Side

Loop of django is triggered by using http requests of a client except for the cases which were special. Loop of websocket and django passes through the queue of messages.

4. Redis subscriber

In the websocket loop message queue is controlled by using a redis subscribers.

5. Redis publisher

In the django loop message is controlled by using the class name as redis publisher.

6. Subscribe to broadcast notifications

This is the simplest form of notification. We need to subscribe to every websocket by using the broadcast channel. The below example shows how we can subscribe to the broadcast notification as follows.

Code:

red_pub = RedisPublisher(facility='web_socket', broadcast=True)
msg = RedisMessage('Web socket')
red_pub.publish_message(msg)

Output:

Subscribe of broadcast notifications

7. Subscribe to user notification

We are initializing web notifications by using URLs. The below example shows how we subscribe to the user notification as follows.

Code:

red_pub = RedisPublisher(facility='web_socket', stud=['ABC', 'XYZ'])
msg = RedisMessage('web socket')
red_pub.publish_message(msg)

Output:

Redis WebSocket - User notification

8. Subscribe Group Notification

The below example shows how we are subscribing to the group notification as follows.

Code:

red_pub = RedisPublisher(facility='web_socket', grp=['stud'])
red_pub.publish_message('web socket')

Output:

Subscribe group notification

9. Subscribe Session Notification

The below example shows how we are subscribing to the session notification as follows.

Code:

red_pub = RedisPublisher(facility='web_socket', session=['w0nqd'])
red_pub.publish_message('web socket')
red_pub.publish_message(msg)

Output:

Subscribe session notification

10. Publish and broadcast the group, session, and user

This configuration used websocket is triggering from the client side.

Code:

red_pub = RedisPublisher()
fac = 'web_socket'
aud = 'stud'
red_pub.fetch_message (request, fac, aud)

Output:

Publish and broadcast the group, session and user

11. Message Echoing

Some application requires holding the state of the object on the server side which is the copy of the javascript object. That message requires the echoing of the message.

12. Safety Considerations

The default setting allows the client to subscribe to publish on every channel. The below example shows safety considerations as follows.

Code:

def get_allowed_channels(request, channels):
if not request.user.is_authenticated():
raise PermissionDenied('Not allowed')

Output:

Redis WebSocket - Safety Considerations

Redis WebSocket Server Application

Redis websocket server is the simple script of nodejs which is used to interact with the redis server by using a web socket. To define the redis server application we need to send the necessary web socket request to the payload as follows.

Code:

{
command: 'SET key1 15',
sessionId: this.sessionId,
date: Date.now()
}

Output:

Redis WebSocket Payload

At the time of defining the web socket server application, we need to send the broadcast notifications to the server. The below example shows how we are sending the broadcast notification as follows.

Code:

pub = RedisPublisher(facility='ws', broadcast=True)
msg = RedisMessage('Web socket')
pub.publish_message (msg)

Output:

Redis WebSocket - Broadcast notification

At the time of creating websocket server application, we need to publish the user and group session as follows.

Code:

pub = RedisPublisher()
fac = 'ws'
aud = 'emp'
pub.fetch_message (request, fac, aud)

Output:

Redis WebSocket - Group Session

Redis WebSocket API

The websocket API was powered by the architecture of microservices, in that redis is used in a primary database and the simple cache. The websocket API is also used in the communication layer between services that we are using in redis streams. To define the websocket API first we need to start the redis server using the below command.

Code:

# redis-server

Output:

Redis WebSocket Architecture

After starting the redis server now in the below example we are defining the websocket API as follows.

Code:

const WebSocket = require('ws');
const redis = require('redis');
const REDIS_SERVER = "redis://localhost:6379";
const WS_PORT = 3000;
var rc = redis.createClient(REDIS_SERVER);
redisClient.subscribe ('app:notifications');
const server = new WebSocket.Server ({ port : WS_PORT });
server.on ('con', function con(ws) {
redisClient.on ('message', function(channel, msg){
console.log(msg);
ws.send(msg);
})
});
console.log ("Started://localhost:"+ WS_PORT);

Output:

Defining Redis WebSocket

Conclusion

In redis, we use publishers and subscribers to create WebSockets. The concept of the publisher and subscriber is simple. The subscriber is a client that has been listening for changes in a set of data. The protocol provides both unidirectional and bidirectional communication channels, making real-time chat applications possible.

Recommended Articles

This is a guide to Redis WebSocket. Here we discuss the introduction, use, steps to create redis WebSocket and server applications. You can also look at the following articles to learn more –

  1. Redis TLS
  2. Redis RDB
  3. Redis INFO
  4. Redis ZRANGE
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • 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

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA

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

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

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

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

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more