http和websocket共用同一端口

webpack熱部署相關的插件

webpack-hot-middleware:是模塊熱替換插件,能夠避免網頁刷新。這個功能並不重要,由於咱們能夠手動刷新。 webpack-dev-middleware:是開發插件,自動增量構建webpack(只從新構建依賴所修改文件的結點,所以可以極大提升構建效率) webpack-dev-server:基於webpack-dev-middlewarehtml

websocket和http共用端口的原理

websocket是http的升級版(upgrade),咱們只須要定製http服務器的upgrade函數便可。讓upgrade函數充當websocket的路由器(多個websocket共用同一端口能夠經過路由器來轉發)。webpack

ws模塊和socket.io

socket.io對websocket協議封裝比較多,ws模塊比較輕量。web

一份優美的代碼

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")
})
相關文章
相關標籤/搜索