node.js 在linux上安装 以及部署项目

环境:centos 系统

第一步: 安装 centos , 按照阿里云的教程 逐步安装即可,https://help.aliyun.com/document_detail/50775.html。

第二步: 安装完后 将server.js 放到  root 目录下  node server.js 发现报错,没有socket.io 错误,处理方式:npm install socket.io  安装 模块。

第三部:这时候server.js 就能运行起来了,但是 linux 需要在后台 运行node项目,就需要安装forever , 安装教程:https://www.aliyun.com/jiaocheng/124522.html

安装后 启动 就完成了。

客户端源码:



  
    
    Socket.IO Example
  
  
    

Socket.IO Example

服务端源码:

var history = new Array();
var clients = [];
var clients_count = 0;

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req,res){
    fs.readFile('./index.html',function(error,data){
		res.writeHead(200,{'Content-Type':'text/html'});
        res.end(data,'utf-8');
    });
}).listen(8889);

console.log('Server running at http://47.75.135.111:8889/');

var io = require('socket.io').listen(server);


io.sockets.on('connection', function (socket) {
    clients_count++;
    console.log('Server1');
 socket.on('message', function (message) {
			console.log(message);
			var isjson = typeof(message);
			if(isjson!="object"){
				message=JSON.parse(message);
			}	
			if (clients[1] == undefined){
                clients[1] = [];
            }
			var no=message.no;
			var check=message.check;
			var crypto = require('crypto');
			var content = no+'niushop';
			var md5 = crypto.createHash('md5');
			md5.update(content);
			var sign = md5.digest('hex');
			/*if(sign!=check || no ==undefined ){
				return false;
			}*/
        if (message.type == "login") {
            if (clients[message.no] == undefined){
                clients[message.no] = [];
            }
			var objConnect = clients[message.no];
		    clients[message.no].push(socket);
		    var itemObj=new Object();
		    itemObj["no"]=message.no;
		    itemObj["time"]=new Date().getTime();
		    history[message.no]=itemObj;
		    console.log(history);
            socket.no = message.no;
            var json = { type:"login", code: 1 };
            socket.json.send(json);
            console.log(clients.length);
        }else if(message.type == "alldata"){
        	console.log(history);
        	socket.json.send(JSON.stringify(history));
        }else{
			console.log('is not  have ');
		}
    });

  socket.on('disconnect', function () {
        clients_count--;
        if(!clients[socket.userid]){
            delete clients[socket.userid];
        }
  });
});

你可能感兴趣的:(php,专区)