1

版本详情

node--------v7.4.0
express-----v4.14
express-ws--v2.0.0

按照官网的例子接入失败,看清楚文档中的

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文件修改

const WSRouter = require('./../dist/socket/base').default;
new WSRouter(server);

./../dist/socket/base文件

/**
 * 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的兼容性并不乐观


jackple
835 声望6 粉丝

热衷于前端学习