简体   繁体   English

无法创建简单的websocket-NodeJS

[英]unable to create simple websocket - NodeJS

I am trying to follow this tutorial: https://www.simonewebdesign.it/101-web-socket-protocol-handshake/ for developing simple websocket protocol. 我正在尝试遵循本教程: https ://www.simonewebdesign.it/101-web-socket-protocol-handshake/,用于开发简单的websocket协议。

I am visiting localhost:1337/index.html but I get: 我正在访问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 找不到网址的网页: http:// localhost:1337 / index.html在 Google上搜索localhost 1337索引HTTP错误404

if I visit this url: file:///C:/Users/.../websocket-demo/index.html 如果我访问此网址: file:///C:/Users/.../websocket-demo/index.html

I atleast see the index.html page being rendered. 我至少看到了呈现的index.html页面。 But in console I get this error: 但是在控制台中,我收到此错误:

WebSocket connection to 'ws://localhost:1337/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED WebSocket与“ ws:// localhost:1337 /”的连接失败:连接建立错误:net :: ERR_CONNECTION_REFUSED

I am not sure what's wrong? 我不确定是怎么了?

I have 3 files: index.html , server.js and client.js 我有3个文件: index.htmlserver.jsclient.js

server.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 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 - consist of forms 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>

Your web server doesn't serve your index.html file. 您的网络服务器不提供index.html文件。

You can see this post to get an idea how to serve static files, or you can just boot up another HTTP server to serve your index file, like with python, the way they suggested in the README file of the tutorial that you are following: https://github.com/simonewebdesign/websocket-demo 您可以查看这篇文章 ,以了解如何提供静态文件,或者您可以启动另一个HTTP服务器来提供索引文件,例如使用python,这是它们在您遵循的教程的README文件中建议的方式: https://github.com/simonewebdesign/websocket-demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM