开始工作:

1.安装node.js

sudo yum install nodejs

或者官网:nodejs.org

安装nodejs-websocket

npm install nodejs-websocket

2.websocket客户端与服务端代码

服务端:app.js

var ws = require('nodejs-websocket');
 
var server = ws.createServer(function(conn) {
 
    conn.on('text', function(str) {
 
        var data = JSON.parse(str);
        console.log(data);
 
        switch (data.type) {
            case 'setname':
                conn.nickname = data.name;
                
                boardcast(JSON.stringify({
                    type: 'serverInformation',
                    message: data.name + ' 加入房间'
                }));
 
                boardcast(JSON.stringify({
                    type: 'chatterList',
                    list: getAllChatter()
                }))
                break;
        
            case 'chat':
                boardcast(JSON.stringify({
                    type: 'chat',
                    name: conn.nickname,
                    message: data.message
                }));
                break;
 
            default:
                break;
        }
    });
 
    conn.on('close', function() {
        boardcast(JSON.stringify({
            type: 'serverInformation',
            message: conn.nickname + ' 离开房间'
        }));
 
        boardcast(JSON.stringify({
            type: 'chatterList',
            list: getAllChatter()
        }))
    });
 
    conn.on('error', function(err) {
        console.log(err);
    });
}).listen(12345);
 
function boardcast(str) {
    server.connections.forEach(function(conn) {
        conn.sendText(str);
    })
}
 
function getAllChatter() {
 
    var chatterArr = [];
 
    server.connections.forEach(function(conn) {
        chatterArr.push({name: conn.nickname});
    })
 
    return JSON.stringify(chatterArr);
}

客户端:index.html

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ChatRoom</title>
    <link href="css/default.css" rel="stylesheet" type="text/css"></link>
</head>
 
<body>
    <div id="header">
        <input type="text" id="name" placeholder="输入用户名">
        <button id="setname" >设置</button>
        <input type="text" id="text" placeholder="输入发送内容">
        <button id="btn">发送</button>
    </div>
    <div id="body">
        <div id="container"></div>
        <div id="chatterlist">
            <p class="chatterlist-head">在线用户(0)</p>
        </div>
    </div>
    <script>
        var ws = null;
 
        document.getElementById('setname').onclick = function () {
            var name = document.getElementById('name').value;
            if (name === '') {
                name = "DefaultN";
            }
 
            ws = new WebSocket('ws://127.0.0.1:12345');
 
            ws.onopen = function () {
                ws.send(JSON.stringify({
                    name: name,
                    type: 'setname'
                }));
            }
 
            document.getElementById('btn').onclick = send;
            document.getElementById('text').onkeyup = function(e) {
                if (e.keyCode !== 13) return;
                send();
            }
 
            ws.onmessage = function (e) {
                var data = JSON.parse(e.data);
 
                if(data.type === 'chatterList') {
                    var list = JSON.parse(data.list);
 
                    var oldList = document.getElementById('chatterlist');
                    oldList.innerHTML = '';
 
                    var p_list_head = document.createElement('p');
                    p_list_head.setAttribute('class', 'chatterlist-head');
                    p_list_head.innerHTML = "在线用户(" + list.length + ")";
                    oldList.appendChild(p_list_head);
 
                    for(var i = 0; i < list.length; i++) {
                        var p_user = document.createElement('p');
                        p_user.innerHTML = list[i].name;
                        p_user.setAttribute('class', 'userlist-item');
                        oldList.appendChild(p_user);
                    }
                } else {
                    console.log(data);
                    var oldContent = document.getElementById('container');
                    oldContent.insertBefore(createChatDiv(data), oldContent.children[0]);
                }
            }
 
            var p_name = document.getElementById('name');
            var p_setname = document.getElementById('setname');
            p_name.innerHTML = name;
            p_setname.setAttribute('disabled', true);
            p_name.setAttribute('disabled', true);
            p_setname.style.display = "none";
            p_name.style.border = "none";
        }
 
        function createChatDiv(data) {
            var div = document.createElement('div');
            var p_time = document.createElement('p');
            var p_content = document.createElement('p');
 
            switch (data.type) {
                case 'serverInformation':
                    p_time.innerHTML = new Date().Format("yyyy-MM-dd hh:mm:ss");  
                    p_content.innerHTML = data.message;
                    break;
                
                case 'chat':
                    p_time.innerHTML = new Date().Format("yyyy-MM-dd hh:mm:ss");  
                    p_content.innerHTML = data.name + ': ' + data.message;
                    break;
 
                default:
                    break;
            }
            
            p_time.setAttribute('class', 'time');
            p_content.setAttribute('class', 'content');
 
            div.appendChild(p_time);
            div.appendChild(p_content);
            return div;
        }
 
        Date.prototype.Format = function (fmt) { //author: meizz 
            var o = {
                "M+": this.getMonth() + 1, //月份 
                "d+": this.getDate(), //日 
                "h+": this.getHours(), //小时 
                "m+": this.getMinutes(), //分 
                "s+": this.getSeconds(), //秒 
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                "S": this.getMilliseconds() //毫秒 
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
 
        function send() {
            if(document.getElementById('text').value === '') return;
            ws.send(JSON.stringify({
                message: document.getElementById('text').value,
                type: 'chat'
            }));
            document.getElementById('text').value = '';
        }
 
    </script>
</body>
 
</html>

一个客户端用到的css:default.css


body{
    height: 100%;
    clear: both;
    margin: 0;
}
 
#header{
    background-color: white;
    position: fixed;
    padding: 10px;
    width: 100%;
    border-bottom: 1px solid #ddd;
}
 
#body{
    padding-top: 51px;
    height: 100%;
    width: 100%;
    overflow: hidden;
}
 
#container{
    min-width: 500px;
    padding-left: 10px;
    padding-right: 10px;
    width: 80% - 20px;
    height: 100%;
    float: left;
}
 
#chatterlist{
    position: fixed;
    right: 0;
    top: 51;
    width: 20%;
    background-color: #f6f6f6;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
}
 
.chatterlist-head{
    margin: 0;
    padding: 5px 0 5px 10px;
    width: 100% - 10px;
    color: white;
    background-color: #00a1b6;
}
 
.userlist-item{
    margin: 0;
    padding-left: 10px;
    padding-top: 5px;
    padding-bottom: 5px;
    font-size: 14px;
    border-bottom: 1px solid #ddd;
}
 
.time{
    width: fit-content;
    padding: 2px 8px 2px 8px;
    font-size: 8px;
    color: gray;
    background-color: #f6f6f6;
    border-radius: 8px;
    margin: 0;
    margin-top: 10px;
}
 
.content{
    width: fit-content;
    padding: 2px 8px 2px 8px;
    font-size: 14px;
    color: #f6f6f6;
    background-color: #00a1b6;
    border-radius: 8px;
    max-width: 70%;
    margin: 0;
    margin-top:5px;
}
 
#btn, #setname{
    height: 30px;
    font-size: 14px;
    border-radius: 10px;
    border: 1px solid #00a1b6;
    color: white;
    padding: 2px 10px 2px 10px;
    background-color: #00a1b6;
    border: none;
    outline: none;
    cursor: pointer;
}
 
#btn:hover{
    color: #00a1b6;
    background-color: white;
    border: 1px solid #00a1b6;
    transition: 0.4s;
}
 
#setname:hover{
    color: #00a1b6;
    background-color: white;
    border: 1px solid #00a1b6;
    transition: 0.4s;
}
 
#name, #text{
    height: 25px;
    width: 100px;
    font-size: 14px;
    border-radius: 10px;
    border: 1px solid #9fafb1;
    box-shadow: #ddd;
    padding-left: 10px;
    outline: none;
}
 
#text{
    width: 400px;
}
 
#name:focus{
    border: 1px solid #00a1b6;
    transition: 1s;
}
 
#text:focus{
    border: 1px solid #00a1b6;
    transition: 1s;
}

3.利用node运行服务端

这里遇到一个小坑,如果js项目运行在服务器上,断开连接后js也自动断开,这里用到一个让js项目一直处于运行状态的命令

nohup node xxx.js &

运行完以后按任意键退出等待输入,就可以继续做其它事情了,但是最后退出的时候,不能直接关闭Xshell,要通过输入exit断开连接,然后关闭Xshell 此时服务端就已经运行,客户端可以通过修改 ws://127.0.0.1:12345 形式进行服务端的连接 这里我吧播放器与聊天页结合的方式呈现了

演示地址:聊天播放器

项目地址:github