无法创建简单的websocket - NodeJS

时间:2017-08-25 16:34:31

标签: javascript node.js websocket

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

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

  

无法找到此本地主页

     

找不到网址的网页:http://localhost:1337/index.html       在Google上搜索localhost 1337索引       HTTP错误404

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

我至少看到正在呈现的index.html页面。但是在控制台中我得到了这个错误:

  

WebSocket连接到' ws:// localhost:1337 /'失败:连接建立错误:net :: ERR_CONNECTION_REFUSED

我不确定是什么错?

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

server.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>

1 个答案:

答案 0 :(得分:2)

您的网络服务器无法提供您的index.html文件。

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