- http
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/html"}); // not necessary but better set
res.end('<div>Hello world!</div>');
}).listen(3000);
console.log('Server has been establish success!');- express
var express = require('express');
var app = express();
app.get('/', function(req, res) { // The First parameter is request url (without host & port), and if not match can't get access, could be regExp too
res.send({
id: 123,
name: 'shawn_dongxiaolong'
}); // automaticly set the Content-Type , don't need to bother about that
}).listen(3000);- ws 1
/*
* Server side
* Methods: ws.send() , ws.on()
* Events: connection, message, error, close
* Attributes: wss.clients
*/
// 使用 wss.clients
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
port: 3000
});
wss.on('connection', function(ws) {
console.log('someone just coming, now has %d client', wss.clients.length
);
ws.on('message', function(data) {
wss.clients.forEach(function(client) {
client.send(data);
});
});
ws.on('close', function() {
console.log('someone just leave, now has %d client', wss.clients.length);
});
ws.on('error', function(err) {
console.log(err);
});
});
console.log('ws estriblish success');/*
* Server side
* Methods: ws.send() , ws.on()
* Events: connection, message, error, close
* Attributes: wss.clients
*/
// 不使用 wss.clients
setIncludes(); // if dont support Array.includes then you need this fallback method
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
port: 3000
});
var clients = [];
wss.on('connection', function(ws) {
if (!clients.includes(ws)) {
clients.push(ws);
}
console.log('someone just coming, now has %d client', clients.length);
ws.on('message', function(data) {
clients.forEach(function(client) {
client.send(data); // consider it as one room , all clients will be in one room and receive all message
});
});
ws.on('close', function() {
clients = clients.filter(function(client) {
return client !== ws;
});
console.log('someone just leave, now has %d client', clients.length);
});
ws.on('error', function(err) {
console.log(err);
});
});
console.log('ws estriblish success');
function setIncludes() {
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}
}<!-- Client side -->
<meta charset="utf-8">
<form id='form'>
<label for="name">昵称</label>
<input id='name' name="name" type="text"></br>
<label for="msg">消息</label>
<input id='msg' name='msg' type="text"></br>
<input type="submit">
</form>
<div id="div"></div>
<script>
/*
* the WebSocket Object
* Attributes: onopen, onmessage, onclose, onerror ...
* Methods: ws.send(), ws.close();
*/
var ws = new WebSocket('ws://127.0.0.1:3000');
var div = getElement('div');
ws.onopen = function() {
console.log('connection founded successfully!')
};
ws.onmessage = function(e) {
var data = JSON.parse(e.data);
div.innerHTML += '<p>' + data.name + ' 说:' + data.msg + '</p>';
};
ws.onerror = function(err) {
console.log(err);
};
ws.onclose = function() {
console.log('connection has been closed!')
};
getElement('form').onsubmit = function() {
ws.send(JSON.stringify({ // must use JSON.stringify & JSON.parse
name: getElement('name').value,
msg: getElement('msg').value
}));
document.getElementById('name').value = '';
document.getElementById('msg').value = '';
return false;
}
function getElement(id) {
return document.getElementById(id);
}
</script>- ws 2
<!-- same as above -->- socket.io
socket.io 有很多好处,最大的好处是在当客户端不支持websocket的时候有自动的回退方法。缺点是前端也必须引用相应的js文件,使用特定的方法,虽然这些方法也很简单,但终归不能直接使用原生的前端websocket写法
安装socket.io client 的方法: bower install https://github.com/socketio/socket.io-client.git
/*
* Server side
* Methods: socket.on & socket.emit,
* Events: connection / connect, disconnect
*/
var http = require('http');
var server = http.createServer().listen(3000);
var io = require('socket.io');
var socketIo = io(server);
/*
* 如果需要跟client约定一个特殊的路径,则使用如下的配置代替上方的配置
* var socketIo = require('socket.io')(3000, { path: '/share'});
*/
socketIo.on('connect', function(client) {
console.log('someone just coming.')
client.on('msg', function(data) {
client.emit('msg', data); // sent it back to this client
console.log("he said: %s , we do nothing just send it back to him", data);
})
client.on('disconnect', function() {
console.log('someone just leave.');
})
});
console.log('WebSocketServer established success');<!-- Client side -->
<meta charset="utf-8">
<form id='form'>
<label for="name">昵称</label>
<input id='name' name="name" type="text"></br>
<label for="msg">消息</label>
<input id='msg' name='msg' type="text"></br>
<input type="submit">
</form>
<div id="div"></div>
<script src="bower_components/socket.io-client/socket.io.js"></script>
<script>
/*
* Methods: socket.on & socket.emit,
* Events: connect, disconnect
*/
var socket = io('http://127.0.0.1:3000');
/*
* 如果需要跟Server约定一个特殊的路径,则使用如下的配置代替上方的配置
* var socket = io.connect('http://127.0.0.1:3000', { path: '/share'})
*/
socket.on('connect', function() {
console.log('connect to 127.0.0.1:3000 success!');
});
socket.on('disconnect', function() {
console.log('connect just closed');
});
var div = getElement('div');
getElement('form').onsubmit = function() {
socket.emit('msg', { // Don't need to JSON.stringify or JSON.parse, socket will automaticly do that work
name: getElement('name').value,
msg: getElement('msg').value
});
document.getElementById('name').value = '';
document.getElementById('msg').value = '';
console.log(msg)
return false;
}
socket.on('msg', function(data) {
console.log(data);
div.innerHTML += '<p>' + data.name + ' 说:' + data.msg + '</p>';
});
function getElement(id) {
return document.getElementById(id);
}
</script> - js
- json
- fs
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile('index.html', function(err, html) {
if (err) {
throw err;
}
res.writeHead(200, {"Content-Type": "text/html"});
res.write(html); // Disadvantages: can't deliver parameters to dynamic change html content
res.end();
})
}).listen(3000);- ejs
// You need
// 1. Set package.json dependencies include ejs & express
// 2.npm install
// 3.your .html file need to rename as .ejs and better put into a floder named 'views'
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', {
id: 123,
name: 'shawn_dongxiaolong'
});
});
app.listen(3000);
console.log('Server establish success, Now open 127.0.0.1:3000 see dose it works!');<!-- source file: views/index.ejs -->
<div>
<p><%- id %></p>
<p><%- name %></p>
</div><!-- open 127.0.0.1:300 and you'll see DOM like below -->
<div>
<p>123</p>
<p>shawn_dongxiaolong</p>
</div>- 函数嵌套
- 递归调用
- step
- sync
- jscex
- promise
var http = require('http');
http.createServer(function(req, res) {
new Promise(function(resolve, reject) {
var match = '\/info';
if (req.url.match(regExp)) {
resolve();
return;
}
reject('wrong url');
}).then(function() {
var msg = 'hello world';
return msg;
}).then(function(msg) {
res.writeHeader('');
res.end(JSON.stringify({
status: 200,
desc: 'success',
data: msg
}));
}).catch(function(err) {
console.log('error : ', err);
res.end(err);
})
}).listen(8888);