NodeJS实现Websocket聊天室

debug("\n**************************");
var Config = {
    portSocket: 5050
};
var websocket = require("nodejs-websocket"),
crypto = require('crypto'),
http = require('http');
var webSocketServer = websocket.createServer(function(conn) {
    if (!login(conn.path)) {
        conn.close();
    }
    conn.on("close",
    function(code, reason) {
        debug("客户端连接失败(用户断开)");
    });
    conn.on("error",
    function(code, reason) {
        debug("客户端连接失败(用户断开)");
    });
    conn.on("text",
    function(msg) {
        try {
            var msgObj = JSON.parse(msg);
            var account = msgObj.account;
            var channel = msgObj.channel;
            var ticket = msgObj.ticket;

            if (sha1("account" + account + "channel" + channel) !== ticket) {
                debug("用户身份验证失败");
            } else {
                switch (msgObj.type) {
                case 'system':
                    webSocketServer.connections.forEach(function(conn) {
                        conn.sendText(msgObj.msg);
                    });
                    break;
                case 'channel':
                    webSocketServer.connections.forEach(function(conn) {
                        var query = new QueryString(conn.path);
                        if (query.channel == msgObj.to) {
                            conn.sendText(msgObj.msg);
                        }
                    });
                    break;
                case 'chat':
                    webSocketServer.connections.forEach(function(conn) {
                        var query = new QueryString(conn.path);
                        if (query.account == msgObj.to) {
                            conn.sendText(msgObj.msg);
                        }
                    });
                    break;
                default:
                    debug("未知的消息类型" + msgObj.type);
                    return;
                }
            }
            //debug(msg);
        } catch(e) {
            debug("消息类型解析失败");
            return;
        }
    });
});
webSocketServer.listen(Config.portSocket);
debug("服务启动成功(" + Config.portSocket.toString() + ")Websocket");
checkConnection();

var httpServer = http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain;charset=utf-8'
    });
    if (req.method.toUpperCase() == 'POST') {
        var postData = "";
        req.on("data", function(data) {
            postData += data;
        });
        req.on("end", function() {
            debug("收到HTTP请求(POST)");
            var msgObj = JSON.parse(postData);
            if (sha1("to-" + msgObj.to + "-type-" + msgObj.type + "-content-" + msgObj.content) == msgObj.ticket || true) {
                switch (msgObj.type) {
                    case 'user':
                        try{
                            webSocketServer.connections.forEach(function(conn) {
                                var query = new QueryString(conn.path);
                                if (query.uid == msgObj.to) {
                                    conn.sendText(msgObj.content);
                                }
                            });
                            debug("单聊消息发送成功");
                        }catch(e){
                            debug("异常");
                        }
                        res.end("Send OK");
                        break;
                    case 'channel':
                        try{
                            webSocketServer.connections.forEach(function(conn) {
                                var query = new QueryString(conn.path);
                                if (query.channel == msgObj.to) {
                                    conn.sendText(msgObj.content);
                                }
                            });
                            debug("频道消息发送成功");
                        }catch(e){
                            debug("异常");
                        }
                        res.end("Send OK");
                        break;
                    case 'system':
                        try{
                            webSocketServer.connections.forEach(function(conn) {
                                //console.log(conn);return;
                                conn.sendText(msgObj.content);
                            });
                            debug("系统消息发送成功");
                        }catch(e){
                            debug("异常");
                        }
                        res.end("Send OK");
                        break;
                    default:
                        debug("系统消息发送失败(Type Error)");
                        res.end("Type Error");
                }
            } else {
                debug("系统消息发送失败(Ticket Error)");
                res.end("Ticket Error");
            }
        });
    } else if (req.method.toUpperCase() == 'GET') {
        res.end("Hamm's Websocket Server.");
    } else {
        res.end("Hamm's Websocket Server.");
    }
});
httpServer.listen(Config.portHttp);
debug("服务启动成功(" + Config.portHttp.toString() + ")HTTP");


function checkConnection() {
    setTimeout(function() {
        debug("当前在线连接数:(" + webSocketServer.connections.length + ")");
        checkConnection();
    },
    10000);
}

function getTime() {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    return hours + ":" + minutes + ":" + seconds;
}

function debug(message) {
    console.log(message);
}

function login(url) {
    var query = new QueryString(url);
    if (sha1("account" + query.account + "channel" + query.channel) == query.ticket) {
        debug("客户端连接成功 "+query.account);
        return true;
    } else {
        debug("客户端连接失败:登录失败)");
        return false;
    }
}

function QueryString(url) {
    var name, value;
    url = url.replace("/?", "");
    var arr = url.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            this[name] = value;
        }
    }
}

function sha1(str) {
    var sha1 = crypto.createHash("sha1"); //定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称;
    sha1.update(str);
    var res = sha1.digest("hex"); //加密后的值d
    return res;
}
<?php 
$ticket=$_COOKIE[ 'ticket'];
$account=$_COOKIE[ 'account']; 
$channel=0; 
if(empty($_COOKIE[ 'ticket']) || empty($_COOKIE[ 'account'])){
    $account=sha1(time().rand(100000,9999999));
    $ticket=sha1( "account".$account. "channel".$channel);
    setcookie("account",$account);
    setcookie( "ticket",$ticket);
    header( "Location: /");
    die();
} 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
        <title>Hello World!</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
        <link rel="stylesheet" href="/static/amazeui/2.7.2/css/amazeui.min.css" />
        <link rel="stylesheet" href="/static/weui/0.4.3/style/weui.min.css">
        <link rel="stylesheet" href="/static/jquery-weui/0.8.2/css/jquery-weui.min.css">
        <style>
        body, html {
            background-color: #eee;
            font-size: 14px;
            width: 100%;
            height: 100%;
            margin: 0;
        }
        * {
            -webkit-touch-callout:none;
            -moz-touch-callout:none;
            -ms-touch-callout:none;
            touch-callout:none;
        }
        img {
            pointer-events: none;
        }
        .radius-3 {
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
        }
        .radius-5 {
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
        }
        .weui_media_desc {
            margin: 0;
            padding: 0;
        }
        .weui_media_info {
            padding: 0;
            margin: 0;
        }
        .weui_tabbar_label {
            padding: 0;
            margin: 0;
        }
        .weui_tab {
            position: fixed;
            left: 0;
            right: 0;
            bottom: 0;
            height: 60px;
        }
        .space-60 {
            height: 60px;
        }
        .weui_cell_bd>p {
            margin: 0;
            padding: 0;
        }
        h4 {
            margin:0;
        }
        .space {
            height: 60px;
        }
        .clear {
            clear: both;
        }
        ul {
            margin:0;
            padding:0;
        }
        .weui_dialog {
            z-index: 1001;
        }
        </style>
        <style>
        html, body {
            background-color: #000;
        }
        .relative {
            position: relative;
        }
        .screen {
            height: 100%;
            margin:10px;
            color: lightgreen;
        }
        .nick {
            color: orangered;
        }
        .input>input {
            color: lightgreen;
            background-color: black;
            border: none;
            outline: none;
            font-weight: bold;
        }
        .error {
            color: orangered;
        }
        .message {
            color: yellow;
        }
        </style>
    </head>
    
    <body>
        <div style="background:#000 url();background-attachment:fixed;z-index:-1;position:fixed;left:0;right:0;top:0;bottom:0;"></div>
        <div style="position:fixed;right:10px;top:10px;">Powered by <a style="color:yellow;" href="https://Hamm.cn" target="_blank">Hamm.cn</a></div>
        <div class="screen" id="screen">
            <div class="item"><span class="nick">Hamm</span> says : <font color=white>Welcome to Hamm's chatroom for programer and productors !</font>

            </div>
        </div>
        <script src="/static/js/fastclick.js"></script>
        <script src="//libs.baidu.com/jquery/1.10.1/jquery.min.js"></script>
        <script src="/static/jquery-weui/0.8.2/js/jquery-weui.min.js"></script>
        <script>
        var Game = {
            name:"Guest",
            now: "ready",
            ready: false,
            socket: null,
            channel: 0,
            dokeydown: function (e) {
                var keynum;
                var keychar;
                var numcheck;

                if (window.event) // IE
                {
                    keynum = e.keyCode
                } else if (e.which) // Netscape/Firefox/Opera
                {
                    keynum = e.which
                }
                if (keynum == 13) {
                    Game.doControl($(".inputbox").val());
                }
            },
            doControl: function (msg) {
                switch (Game.now) {
                    case "Connected":
                        if(!Game.ready){
                            $.confirm('Connect closed,reconnect?','Connect closed',function(){
                                Game.reconnect();
                            });
                        }else{
                            switch(msg){
                                case 'clear':
                                    msg="我清理了我的屏幕。"
                                    break;
                                case 'ls':
                                    msg="我想查看一下目录结构,但是没有权限。"
                                    break;
                                case 'mkdir':
                                    msg="我想创建文件夹,但是没有权限。"
                                    break;
                                default:
                            }
                            Game.socket.send(JSON.stringify({
                                account: '<?php echo $account;?>',
                                channel: '<?php echo $channel;?>',
                                ticket: '<?php echo $ticket;?>',
                                type: 'channel',
                                to: '0',
                                msg: msg
                            }));
                            Game.input();
                        }
                        break;
                    default:
                        Game.error("Error : Some bugs with your input ");
                }
            },
            input: function (status) {
                $(".screen").append(
                    '<div class="input"><input class="inputbox" autocomplete="off" onkeydown="Game.dokeydown(event)" type="text"/></div>');
                Game.status = status;
            },
            showmsg:function(name,msg){
                console.log(msg);
                $(".input").remove();
                $(".screen").append(
                    '<div class="item"><span class="nick">'+name+'</span> says : <font color=white>'+msg+'</font></div>');
                Game.input();
            },
            message: function (msg) {
                $(".screen").append('<div class="warning">' + msg + '</div>');
            },
            error: function (msg) {
                $(".screen").append('<div class="error">' + msg + '</div>');
            },
            checkFocus: function () {
				document.getElementById("screen").scrollTop = document.getElementById("screen").scrollHeight;
                $(".inputbox").focus();
                setTimeout(function () {
                    Game.checkFocus();
                }, 100);
            },
            init: function () {
                Game.now = "Connecting";
                Game.socket = new WebSocket("wss://wss.hamm.cn/?account=<?php echo $account;?>&channel=<?php echo $channel;?>&ticket=<?php echo $ticket;?>");
                Game.socket.onopen = function (evt) {
                    $.hideLoading();
                    $.toast("Connected");
                    Game.now = "Connected";
                    Game.error("Success : Chat server connected success!");
                    Game.input();
                    Game.ready = true;
                    // 监听消息
                    Game.socket.onmessage = function (event) {
                        try{

                            Game.showmsg('who',event.data);return;
                            var obj=JSON.parse(decodeURIComponent(event.data));
                            Game.showmsg(obj.name,obj.content);
                        }catch(e){
                            console.log("error");
                        }
                    };

                    // 监听Socket的关闭
                    Game.socket.onclose = function (event) {
                        Game.ready = false;
                        Game.error("Error : Connect closed.");
                        Game.input();
                        $.confirm('Connect closed,reconnect?','Connect closed',function(){
                            Game.reconnect();
                        });
                    };

                };
            },
            heartBeat: function () {
                Game.loginTimer = setTimeout(function () {
                    if (!Game.ready) {
                        console.log("Closed");
                    } else {
                        $.hideLoading();
                    }
                    Game.heartBeat();
                }, 3000);
            },
            reconnect: function () {
                Game.now = "ReConnecting";
                Game.init();
            },
        };
        window.onload = function () {
            Game.message("Connecting...");
            Game.init();
            Game.checkFocus();
        };
        </script>
    </body>

</html>
<?php
$to=$_REQUEST['to'];
$type=$_REQUEST['type'];
$msg=empty($_REQUEST['msg'])?"???":htmlspecialchars($_REQUEST['msg']);
$name=empty($_REQUEST['name'])?"Guest":htmlspecialchars($_REQUEST['name']);

$msg=strip_tags($msg);
$name=strip_tags($name);
$content=urlencode(json_encode(array("name"=>$name,"content"=>$msg)));

$data=array(
    "to"=>$to,//发送的对象 如果是user就是userid 如果类型是channel就是channelid 如果是system则为空
    "type"=>$type,//user channel system
    "content"=>$content,//内容
    "ticket"=>sha1("to-".$to."-type-".$type."-content-".$content)//签名
);
$data=json_encode($data);
$ret=post("http://hamm.cn:10010",$data);
print_r($ret);
function post($url,$data){
    $ch=curl_init();
    curl_setopt ($ch,CURLOPT_URL ,$url);
    curl_setopt ($ch,CURLOPT_RETURNTRANSFER ,1);
    curl_setopt ($ch,CURLOPT_POST ,1);
	curl_setopt ($ch,CURLOPT_POSTFIELDS ,$data);
    $output=curl_exec($ch);
    curl_close ($ch);
    return $output;
}
?>