Linux环境下Node.js的安装与项目部署指南

发表时间: 2018-05-24 23:41

环境:centos 系统

第一步: 安装 centos , 按照阿里云的教程 逐步安装即可,

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

第三部:这时候server.js 就能运行起来了,但是 linux 需要在后台 运行node项目,就需要安装forever

安装后 启动 就完成了。

客户端源码:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>Socket.IO Example</title>

</head>

<body>

<h1>Socket.IO Example</h1>

<script src="socket.io-client/socket.io1.js"></script>

<script>

var socket = io.connect('https://47.75.135.111:8889');

var dataJson = {type:"alldata", no: "sadfdasfads"};

socket.json.send(dataJson);

socket.on("message", function (message) {

var type = message.type;

alert(message);

});

</script>

</body>

</html>

服务端源码:

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 https://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];

}

});

});