大多数的实时Web应用程序中,服务器和客户端之间的通信发生在响应报文里,或者是对用户行为的响应,或者是从服务器获取数据更新的结果。
安装Socket.IO
$npm install socket.io@0.9.16 –save
package.json文件$npm install
{
"name": "socket-express",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~4.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"jade": "~1.3.0",
"socket.io": "0.9.16"
}
}
在某种程度上,可以认为Socket.IO是另一个服务器,因为他处理的是socket连接,而不是标准的HTTP请求。
app.js文件
//1.导入依赖
var http = require('http');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
//2.导入路由规则
var routes = require('./routes/index');
//3.创建服务器对象
var app = express();
// 4.设置视图引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//5.设置中间件
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
//6.创建Socket.IO对象并实现监听端口建立连接
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//7.Socket服务器的连接建立后,添加事件监听器
messageChange
io.sockets.on('connection', function (socket) {
socket.on('messageChange', function (data) {
console.log(data);
socket.emit('receive', data.message.split('').reverse().join('') );//将字符串逆序
});
});
//8.监听端口启动服务器
app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
路由文件./routes/index
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Socket.io + Express = <3' });
});
module.exports = router;
视图文件./views/layout.jade
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
视图文件./views/index.jade
extends layout
block content
h1= title
p Welcome to
span.received-message #{title}
input(type='text', class='message', placeholder='what is on your mind?', onkeyup='send(this)')
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost');
socket.on('receive', function (message) {
console.log('received %s', message);
document.querySelector('.received-message').innerText = message;
});
var send = function(input) {
console.log(input.value)
var value = input.value;
console.log('sending %s to server', value);
socket.emit('messageChange', {message: value});
}
默认情况下,WebSocket连接可以使用标准端口,HTTP用80,HTTPS用443