基于HTML+jquery+Node.js建立在线聊天室
如题,建立一个基于HTML+JS+Node.js的在线聊天室,使用的编译器:RJ texted
后端建立(Node.js)
开头第一句: nodejs-websocket是Node.js中自带的模板包,但是要自己下载。很简单的cmd指令,在node.js的文件界面,输入以下指令,Node.js会自己下载,然后再Node.js文档中的node-moudules中就可以找到对应的文档。
完成以上步骤,就可以使用编译器进行编译。废话不多说,直接上码
var ws = require("nodejs-websocket") // require 'nodejs-websocket' modules
var msg=null; // initialize msg
var x=0; // used in detect userID
var y=0; // used in PM
var username='';
var userNameObject={};
var number =0;
var AllUserData = new Array();
var AUsername = new Array();
console.log("Start to connect...");
var server = ws.createServer(function (connect) {
connect.on("text",
function(msg){
if(msg)
{
if(msg.slice(0,7)=='userID:') // detect user ID
{
number++;
username=msg.slice(7);
AllUserData.push({ // Store User information in Server
'id':username,
'ws':connect
});
AUsername.push(username);
userNameObject[username]=connect;
server.connections.forEach(function (conn) //Announce user come in
{
console.log("connection : " + username)
conn.sendText('System'+'userID'+'Welcome '+username+' Join in the chating room. ' + 'Now, here is ' + number);
})
}
else{
var Touser = msg.split("|")[1];
var Msg = msg.split("|")[0];
for(x in userNameObject){// send the information in the chatting room
if(connect==userNameObject[x]){
server.connections.forEach(function (conn) {
console.log(x + ' > ' + Touser + ' : ' + Msg);
conn.sendText(x + 'userID' + Msg + 'To' + Touser );
})
}
}
}
}
});
connect.on("close", function (code, reason) { // Disconnect Server and detect
number--;
var dcname;
for (var i=0 in AllUserData) {
dcname = AllUserData[i].id;
if (AllUserData[i].ws == connect) {
server.connections.forEach(function (conn) {
conn.sendText( 'System'+ 'userID' + dcname + ' has disconnected in this chatting room! '+ ' Now, here is ' + number);
console.log("Connection : " + dcname + " closed")
delete AllUserData[i];
})
if(number == 0){// if there is no server the