ws +表达如何连接到websocket

时间:2017-10-22 23:57:47

标签: node.js websocket

我第一次尝试使用网络套接字,经过一些研究后我决定使用ws。

我也使用快递,但我没有看到任何特别之处,只有当我在服务器端使用它时(我相信但我仍然对网络套接字有点困惑)。我只需要连接到Web套接字并发送ping请求并等待响应。

我有一个默认的快递申请表:

bin/www

#!/usr/bin/env node

const app = require("../app");
const debug = require("debug")("myapp:server");
const http = require("http");
const WebSocket = require("ws");
const ws = new WebSocket("ws://address-to-connect");

var port = normalizePort(process.env.PORT || "3000");
app.set("port", port);

var server = http.createServer(app);

server.listen(port);
server.on("error", onError);
server.on("listening", onListening);

function normalizePort(val) {
    let port = parseInt(val, 10);

    if (isNaN(port)) {
        return val;
    }

    if (port >= 0) {
        return port;
    }

    return false;
}

function onError(error) {
    if (error.syscall !== "listen") {
        throw error;
    }

    var bind = typeof port === "string"
        ? "Pipe " + port
        : "Port " + port;

    switch (error.code) {
        case "EACCES":
            console.error(bind + " requires elevated privileges");
            process.exit(1);
            break;
        case "EADDRINUSE":
            console.error(bind + " is already in use");
            process.exit(1);
            break;
        default:
            throw error;
    }
}

function onListening() {
    let addr = server.address();
    let bind = typeof addr === "string"
        ? "pipe " + addr
        : "port " + addr.port;

    debug("Listening on " + bind);

    ws.on("open", function open() {
        if (error) throw error;

        ws.send("PING");
    });

    ws.on("message", function incoming(data) {
        if (error) throw error;

        console.log(data);
    });
}

然而,这只会让我误以为events.js:182 throw er; // Unhandled 'error' event Error: connect ECONNREFUSED

我尝试研究这个错误,并从我收集的内容中了解了一个正在使用的端口,但这是我运行的唯一应用程序。

如果需要,我的app.js看起来像:

const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(function (err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get("env") == "development" ? err : {};

    res.status(err.status || 500);
});

module.exports = app;

0 个答案:

没有答案