Build a Realtime Editor Using Socket.IO

We will use SocketIO to stream the changes in the text in realtime, so users can see them instantly. Read on.

Project setup

We need to have Nodejs installed in our machine if you don’t have it in your machine go to Nodejs download pageand download the binary for your machine.

Now, we have the Nodejs installed, we will scaffold a new project:

mkdir realtime-editor
cd realtime-editor
npm init --y

The last command creates a package.json file in the realtime-editor project folder.

Installing SocketIO

Now, we will install SocketIO:

npm i socket.io

Socket.IO enables real-time bidirectional event-based communication. It consists of:

Next, we install the client library for SocketIO.

npm i socket.io-client

Building the server

The server will be responsible for routing our socket streams to all other sockets connected to the server socket. The server will listen to the connection on a port, and establish io connections:

const log = console.log

// initialize http server, socket.io and port number
const http = require('http').createServer()
const io = require('socket.io')(http)
const port = 3000
http.listen(port, () => log(`server listening on port: ${port}`))
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
io.on('disconnect', (evt) => {
    log('some people left')
})

We set up a connection event, the function callback has a socket argument. The socket registers a message event, it has a handler function that broadcast the data evt passed to it to all other sockets connected to the server when the message event is fired.

Building the client

We have index.html:

<html>
<title>Realtime Editor/Collaboration</title>

<body>
    <h3>Realtime Editor/Collaboration</h3>
    <div>
        <textarea rows="30" cols="50" id="editor" style="background-color:dimgrey;color:white" placeholder="Type Your Text..."></textarea>
    </div>
</body>
<script src="../node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="./client.js"></script>
</html>

See the textarea, that’s where we will type in our text. It has id editor. We make textarea have the background color dimgrey, and the text color is white.

Next, we import the socket.io-client via the script tag. Lastly, we import the client.js.

Let’s create client.js and add some code:

// client.js

var socket = io('http://localhost:3000');
const l = console.log
function getEl(id) {
    return document.getElementById(id)
}
const editor = getEl("editor")
editor.addEventListener("keyup", (evt) => {
    const text = editor.value
    socket.send(text)
})
socket.on('message', (data) => {
    editor.value = data
})

We initialized a connection to our server, then we got hold of the textarea in the DOM via its id editor. We added an event listener keyup with a callback function, this function will be executed when we type in the textarea. This callback retrieves the text const text = editor.value in the textarea via it’s HTMLTextareaElement, then the text is sent over the socket stream socket.send(text).

We registered a message event with a handler that sets the text in the textarea with the data it receives.

Now, all sockets register the message event so when a user in the site types a character in the textarea, the text in the user’s textarea is sent over the socket to the server. The server then broadcasts the text to all connected users via the code:

...
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
...

As all users have a message event they are listening to, the message handler will be executed because the server emitted a message event, so all user’s textarea will be set with the text passed over the socket connection.

With these now, all users will see changes and edits by other users realtime. People can work on a document realtime. Writes can work on a blog post, article, news or novel realtime.

Running the app

Type the below command to run the server.js file:

node server

Now, open your browser and load index.htmlon it. Open another browser and load the index.html

Stack the browser windows side by side, then type a text in one browser, you will see it appear in the other browser. Anything you do in one browser will reflect realtime in the other browser, whether it is writing, deleting, etc

Conclusion

That is it with our real-time collaboration platform. You see how easy it is to implement most of the sophisticated platform in simple terms.

The main code here, was just to detect when a character is typed in, then send the text over the socket stream. The server socket having a message event registered sends the text stream over to all connected sockets. Then, all users registered the message event, will get the text stream from the server and set the textarea with the text stream.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me.

Thanks !!!

Recommended Reading

Build a Real-time Voting App with Pusher, Node and Bootstrap

Build a Slack Polling App with Airtable, Standard Library, and Node.js

Node 12 - What Are The New Improvements And Features?

Learn full about Crash course on REST, GraphQL and Graphback

React + Node.js - Drag and Drop Multiple Files Upload

We will use SocketIO to stream the changes in the text in realtime, so users can see them instantly. Read on.

Project setup

We need to have Nodejs installed in our machine if you don’t have it in your machine go to Nodejs download pageand download the binary for your machine.

Now, we have the Nodejs installed, we will scaffold a new project:

mkdir realtime-editor
cd realtime-editor
npm init --y

The last command creates a package.json file in the realtime-editor project folder.

Installing SocketIO

Now, we will install SocketIO:

npm i socket.io

Socket.IO enables real-time bidirectional event-based communication. It consists of:

Next, we install the client library for SocketIO.

npm i socket.io-client

Building the server

The server will be responsible for routing our socket streams to all other sockets connected to the server socket. The server will listen to the connection on a port, and establish io connections:

const log = console.log

// initialize http server, socket.io and port number
const http = require('http').createServer()
const io = require('socket.io')(http)
const port = 3000
http.listen(port, () => log(`server listening on port: ${port}`))
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
io.on('disconnect', (evt) => {
    log('some people left')
})

We set up a connection event, the function callback has a socket argument. The socket registers a message event, it has a handler function that broadcast the data evt passed to it to all other sockets connected to the server when the message event is fired.

Building the client

We have index.html:

<html>
<title>Realtime Editor/Collaboration</title>

<body>
    <h3>Realtime Editor/Collaboration</h3>
    <div>
        <textarea rows="30" cols="50" id="editor" style="background-color:dimgrey;color:white" placeholder="Type Your Text..."></textarea>
    </div>
</body>
<script src="../node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="./client.js"></script>
</html>

See the textarea, that’s where we will type in our text. It has id editor. We make textarea have the background color dimgrey, and the text color is white.

Next, we import the socket.io-client via the script tag. Lastly, we import the client.js.

Let’s create client.js and add some code:

// client.js

var socket = io('http://localhost:3000');
const l = console.log
function getEl(id) {
    return document.getElementById(id)
}
const editor = getEl("editor")
editor.addEventListener("keyup", (evt) => {
    const text = editor.value
    socket.send(text)
})
socket.on('message', (data) => {
    editor.value = data
})

We initialized a connection to our server, then we got hold of the textarea in the DOM via its id editor. We added an event listener keyup with a callback function, this function will be executed when we type in the textarea. This callback retrieves the text const text = editor.value in the textarea via it’s HTMLTextareaElement, then the text is sent over the socket stream socket.send(text).

We registered a message event with a handler that sets the text in the textarea with the data it receives.

Now, all sockets register the message event so when a user in the site types a character in the textarea, the text in the user’s textarea is sent over the socket to the server. The server then broadcasts the text to all connected users via the code:

...
io.on('connection', (socket) => {
    log('connected')
    socket.on('message', (evt) => {
        log(evt)
        socket.broadcast.emit('message', evt)
    })
})
...

As all users have a message event they are listening to, the message handler will be executed because the server emitted a message event, so all user’s textarea will be set with the text passed over the socket connection.

With these now, all users will see changes and edits by other users realtime. People can work on a document realtime. Writes can work on a blog post, article, news or novel realtime.

Running the app

Type the below command to run the server.js file:

node server

Now, open your browser and load index.htmlon it. Open another browser and load the index.html

Stack the browser windows side by side, then type a text in one browser, you will see it appear in the other browser. Anything you do in one browser will reflect realtime in the other browser, whether it is writing, deleting, etc

Conclusion

That is it with our real-time collaboration platform. You see how easy it is to implement most of the sophisticated platform in simple terms.

The main code here, was just to detect when a character is typed in, then send the text over the socket stream. The server socket having a message event registered sends the text stream over to all connected sockets. Then, all users registered the message event, will get the text stream from the server and set the textarea with the text stream.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me.

Thanks !!!

Recommended Reading

Build a Real-time Voting App with Pusher, Node and Bootstrap

Build a Slack Polling App with Airtable, Standard Library, and Node.js

Node 12 - What Are The New Improvements And Features?

Learn full about Crash course on REST, GraphQL and Graphback

React + Node.js - Drag and Drop Multiple Files Upload

#node-js #javascript

Build a Realtime Editor Using Socket.IO
36.00 GEEK