javascript - 无法创建简单的 websocket - NodeJS

标签 javascript node.js websocket

我正在尝试遵循本教程:https://www.simonewebdesign.it/101-web-socket-protocol-handshake/用于开发简单的 websocket 协议(protocol)。

我正在访问localhost:1337/index.html,但我得到:

This localhost page can’t be found

No web page was found for the web address: http://localhost:1337/index.html Search Google for localhost 1337 index HTTP ERROR 404

如果我访问此网址:file:///C:/Users/.../websocket-demo/index.html

我至少看到了正在渲染的index.html页面。但在控制台中我收到此错误:

WebSocket connection to 'ws://localhost:1337/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

我不知道出了什么问题?

我有 3 个文件:index.htmlserver.jsclient.js

服务器.js

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
  console.log('Received request from ' + request.url);
  response.writeHead(404);
  response.end();
});

server.listen(1337, function() {
    console.log('Server is listening on port 1337.');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false // because security matters
});

function isAllowedOrigin(origin) {
  console.log('Connection requested from origin ' + origin);

  valid_origins = [
    'http://localhost:8080',
    '127.0.0.1',
    'null'
  ];

  if (valid_origins.indexOf(origin) != -1) {
    console.log('Connection accepted from origin ' + origin);
    return true;
  }

  console.log('Origin ' + origin + ' is not allowed.')
  return false;
}

wsServer.on('connection', function(webSocketConnection) {
  console.log('Connection started.');
});

wsServer.on('request', function(request) {

  var connection = isAllowedOrigin(request.origin) ?
    request.accept('echo-protocol', request.origin)
    : request.reject();

  connection.on('message', function(message) {

    var response = '';
    console.log('Received Message: ' + message.utf8Data);

    if (message.type === 'utf8') {

      switch (message.utf8Data) {
        case 'hi':
          response = 'Hey there';
          break;
        case 'hello':
          response = 'Heya!';
          break;
        case 'xyzzy':
          response = 'Nothing happens.';
          break;
        case 'desu':
          response = 'Keep typing, man. Keep typing.';
          break;
        default:
          response = "Hello. Uh... what am I supposed to do with '" +
          message.utf8Data + "'?";
      }
      connection.sendUTF(response);
    }
  });
  connection.on('close', function(reasonCode, description) {
      console.log(connection.remoteAddress + ' has been disconnected.');
  });
});

client.js

(function () {

  var ws = new WebSocket('ws://localhost:1337', 'echo-protocol');

  ws.onopen = function (event) {
    console.log('Connection opened.');
  }

  ws.onmessage = function (event) {
    console.log('Response from server: ' + event.data);
  }

  ws.onclose = function (event) {
    console.log('Connection closed.');
  }

  ws.onerror = function (event) {
    console.log('An error occurred. Sorry for that.');
  }

  WebSocket.prototype.sendMessage = function (message) {
    this.send(message);
    console.log('Message sent: ' + message);
  }

  document.getElementById('send').addEventListener('click', function (event) {
    event.preventDefault();
    var message = document.getElementById('message').value;
    ws.sendMessage(message);
  });

})();

index.html - 由表单组成

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>WebSocket Client Demo</title>
</head>
<body>

  <h1>WebSocket Client</h1>

  <form>
    <label for="message">Send a message</label>
    <input id="message" name="message" type="text">
    <button id="send" name="send">Send</button>
  </form>

  <script src="client.js"></script>
</body>
</html>

最佳答案

您的网络服务器不为您的 index.html 文件提供服务。

您可以看到this post了解如何提供静态文件,或者您可以启动另一个 HTTP 服务器来提供索引文件,就像使用 python 一样,按照他们在您正在关注的教程的自述文件中建议的方式:https://github.com/simonewebdesign/websocket-demo

关于javascript - 无法创建简单的 websocket - NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45885888/

相关文章:

java - 创建独立的 Java websocket 客户端端点?

javascript - 工具提示无法正常工作谷歌饼图

javascript - 使用 arcTo() 在 Kinetic.js 中给我一个错误

javascript - 有没有办法真正暂停 readline?

node.js - Metalsmith - 静态站点生成器 - 配置

mysql - 使用 include 在何处进行 Sequelize

websocket - 使用 Apollo 和 GraphQL 设置安全 (wss) websockets 服务器

javascript - Node HTTP 和 WS 服务器未按预期升级连接

javascript - 如何为选项卡设置渐变颜色?

javascript - 如何在发出 http 请求之前对复选框点击进行排队?