Saturday, 8 April 2017

Change font color per client/browser using node.js websocket

I'm trying to create a online chat application using websocket for node.js. Right now it is working but I want to extend the functionality so that when I open it from another browser(client) it will generate a different color text so i can easily distinguish who is who. So far I have this code.

Thanks!

<!--index.html-->
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="minimum-scale=1.0, width=device-width, maximum-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8">
    <title>Websocket</title>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
<h1>Websocket</h1>
<div class="messages"></div>
<form action="javascript:void(0)">
    <label for="message">&gt;</label>
    <input type="text" id="message" required autofocus />
</form>
<script src="ws-client.js"></script>
</body>
</html>

style.css

body {
    background-color: black;
    color: #0F0;
    font-family: verdana;
}

body input,
body label {
    display: block;
}

h1 {
    text-align: center;
}


input {
    outline: none;
    border: none;
    background-color: black;
    color: #0F0;
    padding: 1em .5em;
    display: block;
    font-size: 1.5em;
    -webkit-box-flex: 1;
    -webkit-flex-grow: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
}

label {
    display: block;
    padding: 1em .5em;
    font-size: 1.5em;
}

div.messages {
    margin-left: 1em;
}

form {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
}

ws.js

var WebSocketServer = require("ws").Server; 
var wss = new WebSocketServer({ port: 3000 }); 

wss.on("connection", function(ws) {
    ws.on("message", function (message)
    {
        if (message === 'exit'){
            ws.close();
        } else{
            wss.clients.forEach(function(client) {
                client.send(message);
            });
        }       
    });
    ws.send("Welcome to cyber chat");
});

ws-client.js

var ws = new WebSocket("ws://localhost:3000");

ws.onopen = function(){
    setTitle("Connected with chat");
};

ws.onclose=function(){
    setTitle("null");
};

ws.onmessage=function(payload){
    printMessage(payload.data);
};

document.forms[0].onsubmit = function () {
    var input = document.getElementById('message');
    ws.send(input.value);
    input.value = '';
};

function setTitle(title) {
    document.querySelector('h1').innerHTML = title;
}

function printMessage(message) {
    var p = document.createElement('p');
    p.innerText = message;
    document.querySelector('div.messages').appendChild(p);
}



via user7836693

No comments:

Post a Comment