KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

WebSocket Chat Client JS

Introduction

The screenshot below shows you what our chat application interface will look like

You do not need a web server to run the client application but we will run it from the web server.

Create a file named index.php in the wsserver

Add the following code

<!DOCTYPE html>
<html>
    <head>
        <title>WebSocket PHP Open Group Chat App</title>
        <link type="text/css" rel="stylesheet" href="style.css" />
        <script src="websocket_client.js"></script>
    </head>
    <body onload="javascript:WebSocketSupport()">
        <div id="ws_support"></div>

        <div id="wrapper">
            <div id="menu">
                <h3 class="welcome">Welcome to WebSocket PHP Open Group Chat App v1</h3>
            </div>

            <div id="chatbox"></div>

            <div id ="controls">
                <label for="name"><b>Name</b></label>
                <input name="chatname" type="text" id="chatname" size="67" placeholder="Type your name here"/>
                <input name="msg" type="text" id="msg" size="63" placeholder="Type your message here" />
                <input name="sendmsg" type="submit"  id="sendmsg" value="Send" onclick="doSend(document.getElementById('msg').value)" />
            </div>
        </div>
    </body>
</html>

The above is standard HTML and JavaScript code. Refer to WebSocket Example if you are not familiar with interacting with WebSocket servers using JavaScript and HTML.

Create a new file named style.css

Add the following code

body {
    font:12px arial;
    color: #222;
    text-align:center;
    padding:35px; }

#controls, p, span {
    margin:0;
    padding:0; }

input { font:12px arial; }

a {
    color:#0000FF;
    text-decoration:none; }

a:hover { text-decoration:underline; }

#wrapper, #loginform {
    margin:0 auto;
    padding-bottom:25px;
    background:#66CCFF;
    width:504px;
    border:1px solid #ACD8F0; }

#chatbox {
    text-align:left;
    margin:0 auto;
    margin-bottom:25px;
    padding:10px;
    background:#fff;
    height:270px;
    width:430px;
    border:1px solid #ACD8F0;
    overflow:auto; }

#chatname {
    width:395px;
    border:1px solid #ACD8F0;
    margin-left: 25px;
    float:left;}

#msg {
    width:395px;
    border:1px solid #ACD8F0; }

#submit { width: 60px; }

Open http://localhost/wsserver in browser such as Google Chrome or Firefox. You should be able to get the screen shot shown above.

We have not yet added the functionality so it will not work.

Create a new file named websocket_client.js

Add the following code

var output;

var websocket;

function WebSocketSupport()
{
    if (browserSupportsWebSockets() === false) {
        document.getElementById("ws_support").innerHTML = "<h2>Sorry! Your web browser does not supports web sockets</h2>";

        var element = document.getElementById("wrapper");
        element.parentNode.removeChild(element);

        return;
    }

    output = document.getElementById("chatbox");

    websocket = new WebSocket('ws:localhost:999');

    websocket.onopen = function(e) {
        writeToScreen("You have have successfully connected to the server");
    };


    websocket.onmessage = function(e) {
        onMessage(e)
    };

    websocket.onerror = function(e) {
        onError(e)
    };
}

function onMessage(e) {
    writeToScreen('<span style="color: blue;"> ' + e.data + '</span>');
}

function onError(e) {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + e.data);
}

function doSend(message) {
    var validationMsg = userInputSupplied();
    if (validationMsg !== '') {
        alert(validationMsg);
        return;
    }
    var chatname = document.getElementById('chatname').value;

    document.getElementById('msg').value = "";

    document.getElementById('msg').focus();

    var msg = '@<b>' + chatname + '</b>: ' + message;

    websocket.send(msg);

    writeToScreen(msg);
}

function writeToScreen(message) {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
}

function userInputSupplied() {
    var chatname = document.getElementById('chatname').value;
    var msg = document.getElementById('msg').value;
    if (chatname === '') {
        return 'Please enter your username';
    } else if (msg === '') {
        return 'Please the message to send';
    } else {
        return '';
    }
}

function browserSupportsWebSockets() {
    if ("WebSocket" in window)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Refer to WebSocket Example if you do not understand the above code

Our client application is now ready for testing.

Open your web browser

Enter the URL http://localhost/wsserver

You will get the following window

FireFox Browser WebSocket Support

Open another tab and enter the same URL

Enter user names in both chat tabs and try sending messages

You will get results similar to the ones shown below

FireFox Browser WebSocket Support

FireFox Browser WebSocket Support

Switch back to the to the command prompt window where the server is running You should see results similar to the ones shown below

FireFox Browser WebSocket Support

Tutorial History

Tutorial version 1: Date Published 2015-08-20