http和websocket共用同一端口

webpack热部署相关的插件

webpack-hot-middleware:是模块热替换插件,可以避免网页刷新。这个功能并不重要,因为我们可以手动刷新。
webpack-dev-middleware:是开发插件,自动增量构建webpack(只重新构建依赖所修改文件的结点,因此能够极大提高构建效率)
webpack-dev-server:基于webpack-dev-middleware

websocket和http共用端口的原理

websocket是http的升级版(upgrade),我们只需要定制http服务器的upgrade函数即可。让upgrade函数充当websocket的路由器(多个websocket共用同一端口可以通过路由器来转发)。

ws模块和socket.io

socket.io对websocket协议封装比较多,ws模块比较轻量。

一份优美的代码

var express = require("express")
var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var ws = require("ws")
var http = require("http")


var webpackDevConfig = require('./webpack.config')
var httpHandler = require("./httpHandler")

//定义好express app
app = express()
var compiler = webpack(webpackDevConfig)
app.use(webpackDevMiddleware(compiler))

//设置静态资源
app.use(express.static("dist"))
app.use(express.static("pages"))

httpHandler(app)//注册一系列URL到函数的映射

//定义server
var server = http.createServer(app)
const crawlingWs = new ws.Server({noServer: true})


//定义server的事件
crawlingWs.on("connection", function (conn) {
    console.log("user connected")
    conn.on('message', function incoming(message) {
        console.log('received: %s', message);
    })
})
server.on('upgrade', function upgrade(request, socket, head) {
    const pathname = url.parse(request.url).pathname;
    if (pathname === '/crawling') {
        wsServer1.handleUpgrade(request, socket, head, function done(conn) {
            wsServer1.emit('connection', conn, request);
        });
    } else {
        console.log("没有这样的wss处理器")
        socket.destroy();
    }
});


server.listen(80, function () {
    console.log("http://localhost/search.html")
})
展开阅读全文

没有更多推荐了,返回首页