版本詳情html
node--------v7.4.0 express-----v4.14 express-ws--v2.0.0
按照官網的例子接入失敗,看清楚文檔中的node
server: Optional. When using a custom http.Server, you should pass it in here, so that express-ws can use it to set up the WebSocket upgrade handlers. If you don't specify a server, you will only be able to use it with the server that is created automatically when you call app.listen.
bin/www文件修改web
const WSRouter = require('./../dist/socket/base').default; new WSRouter(server);
./../dist/socket/base文件express
/** * WebSocket router */ import express from 'express'; const app = express(); const router = express.Router(); import expressWS from 'express-ws'; export default class WSRouter { constructor(server) { this.server = server; return this.exec(); } exec() { expressWS(app, this.server); router.ws('/', (ws, req) => { ws.on('message', msg => { ws.send(msg); }) }); app.use('/common', router); } }
test.html文件服務器
<html> <head> <title>test</title> <!--禁止請求 favicon.ico --> <link rel="icon" href="data:image/ico;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII="> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="format-detection" content="telephone=no"> <meta content="email=no" name="format-detection"> <meta http-equiv="Cache-Control" content="no-siteapp"> <style> body { text-align: center; padding: 20px; } button { width: 100%; padding: 20px 0; color: #fff; font-size: 20px; background: green; margin-top: 20px; border: 0; border-radius: 5px; } </style> </head> <body> <div id="mess"></div> <button id="btn">按鈕</button> </body> <script> const mess = document.getElementById("mess"); let time = 1; if(window.WebSocket){ const ws = new WebSocket('ws://localhost:3000/common'); ws.onopen = function(e){ console.log("鏈接服務器成功"); } ws.onclose = function(e){ console.log("服務器關閉"); } ws.onerror = function(e){ console.log("鏈接出錯", e); } ws.onmessage = function(e){ mess.innerHTML = "鏈接成功"; console.log(e.data); } document.getElementById('btn').addEventListener('click', function (e) { e.preventDefault(); ws.send(time ++); }, false); } </script> </html>
下次接入socket.io看看,畢竟Websocket的兼容性並不樂觀app