PieSocket logo

Create a real-time chat web-app with WebSocket

To demonstrate how to subscribe to our WebSocket endpoint with Javascript, We will create a simple chat script, in just 5 minutes.

WebSocket API is supported in all modern browsers and we do not need to install any libraries to subscribe to a WebSocket channel.

Scroll to the bottom of this page for the full code of this demo chat web-app.

Create an HTML file

Create an HTML file, lets say piesocket.html and add some a basic web page structure to it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PieSocket Tester</title>
</head>
<body>

</body>
</html>

Connect to the WebSocket server

Add the following Javascript into a script tag inside the HTML file to connect to the WebSocket channel

var apiKey = 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm';
var channelId = 1;
var piesocket = new WebSocket(`wss://connect.websocket.in/v3/${channelId}?api_key=${apiKey}&notify_self`);

Listen for events

Let's add some code that will be triggered whenever we receive a message on the WebSocket channel.

var apiKey =  piesocket.onmessage = function(message) {
    alert(`Incoming message: ${message.data}`);
}

Add the chat UI

Let's add some more HTML to build a minimal chat UI

<div id="chatLog">

</div>
<div id="chatFormContainer">
    <form id="chatForm">
        <input id="chatMessage" placeholder="Type  message and press enter..." type="text">
    </form>
</div>

Handle events

Let's modify our onmessage so it handles our messages as needed

piesocket.onmessage = function(message) {
    var payload = JSON.parse(message.data);
    console.log(payload);

    if (payload.sender == username) {
        payload.sender = "You";
    }

    if (payload.event == "new_message") {

        //Handle new message
        chatLog.insertAdjacentHTML('afterend', `
${payload.sender}: ${payload.text}
`); } else if (payload.event == 'new_joining') { //Handle new joining chatLog.insertAdjacentHTML('afterend', `
${payload.sender} joined the chat
`); } }

Trigger events

The Websocket client is now ready to handle new_message and new_joining events, let's trigger those events by publishing a message to our WebSocket channel.

We will publish new_message when a user submits the chat form by pressing enter.

And, new_joining when someone joins the channel.

{warning} We should publish messages from server-side for better security.

For the sake of simplicity of this demo, we have enabled C2C communication for the demo API from PieSocket API settings, so that we can send messages directly from the WebSocket client without a backend.

Let's publish!

Publish new_joining

This is triggered when the websocket connection is established.

var username = `user_${getRandomNumber()}`
piesocket.onopen = function() {
    console.log(`Websocket connected`);

    //Let others know I have arrived!
    piesocket.send(JSON.stringify({
        event: 'new_joining',
        sender: username,
    }));
}

Publish new_message

This function is triggered when the form is submitted.

function sendMessage(e) {
    e.preventDefault();

    var message = document.getElementById('chatMessage').value;

    //Let others know what I have to say
    piesocket.send(JSON.stringify({
        event: 'new_message',
        sender: username,
        text: message
    }));
}

And this completes our simple WebSocket chat web-app

Wrapping up!

To test this web-app, copy the full code given below and save it into an HTML file. Then, open the HTML file into multiple tabs, send message from one tab and check in other tabs. Voila!

Here is the full working code, Happy chatting with yourself!

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test PieSocket</title>
    <style>
        #chatFormContainer {
            text-align: center;
            position: fixed;
            bottom: 5px;
            left: 5px;
            right: 5px;
        }

        #chatFormContainer input {
            display: inline-block;
            width: 90%;
            padding: 20px;
        }
    </style>
</head>

<body>
    <div id="chatLog">

    </div>
    <div id="chatFormContainer">
        <form id="chatForm">
            <input id="chatMessage" placeholder="Type  message and press enter..." type="text">
        </form>
    </div>
    <script>
        var username = `user_${getRandomNumber()}`
        var apiKey = 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm';
        var channelId = 1;
        var piesocket = new WebSocket(`wss://connect.websocket.in/v3/${channelId}?api_key=${apiKey}&notify_self`);

        var chatLog = document.getElementById('chatLog');
        var chatForm = document.getElementById('chatForm');
        chatForm.addEventListener("submit", sendMessage);

        piesocket.onopen = function() {
            console.log(`Websocket connected`);
            piesocket.send(JSON.stringify({
                event: 'new_joining',
                sender: username,
            }));
        }
        piesocket.onmessage = function(message) {
            var payload = JSON.parse(message.data);
            console.log(payload);

            if (payload.sender == username) {
                payload.sender = "You";
            }

            if (payload.event == "new_message") {

                //Handle new message
                chatLog.insertAdjacentHTML('afterend', `<div> ${payload.sender}: ${payload.text} <div>`);

            } else if (payload.event == 'new_joining') {

                //Handle new joining
                chatLog.insertAdjacentHTML('afterend', `<div> ${payload.sender} joined the chat<div>`);

            }
        }

        function getRandomNumber() {
            return Math.floor(Math.random() * 1000);
        }

        function sendMessage(e) {
            e.preventDefault();

            var message = document.getElementById('chatMessage').value;

            piesocket.send(JSON.stringify({
                event: 'new_message',
                sender: username,
                text: message
            }));
        }
    </script>
</body>
</html>

Help

Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.