SockJS nginx 502 Bad Gateway

时间:2016-10-04 09:12:36

标签: node.js nginx websocket sockjs

我正在尝试使用SockJS从几个教程中创建一个简单的聊天应用程序。 但是当客户端尝试连接服务器502时,在此URL https://ws.example.com/chat/echo/info?t=1475571844728(根据控制台)发生错误的网关错误。 我尝试了没有sockjs模块的简单节点应用程序来测试它正在运行的反向代理。这是我的代码。

服务器

var http = require('https');
var sockjs = require('sockjs');
var fs = require("fs");

var options = {
  key: fs.readFileSync('ssl.key'),
  cert: fs.readFileSync('ssl.crt')
};

var clients = {};

function broadcast(message){
  for (var client in clients){
    clients[client].write(JSON.stringify(message));
  }
}

var echo = sockjs.createServer();

echo.on('connection', function(conn) {

  clients[conn.id] = conn;

  conn.on('data', function(message) {
    console.log(message);
    broadcast(JSON.parse(message));
  });

  conn.on('close', function() {
    delete clients[conn.id];
  });

});

var server = http.createServer();

echo.installHandlers(server, {prefix:'/echo'});

server.listen(5959, '0.0.0.0');

客户端

var sock = new SockJS('https://ws.example.com/chat/echo');
sock.onopen = function() {
  console.log('open');
};
sock.onclose = function() {
  console.log('close');
};

sock.onmessage = function(e) {
  var content = JSON.parse(e.data);
  $('#chat-content').val(function(i, text){
    return text + 'User ' + content.username + ': ' + content.message + '\n';
  });

};

function sendMessage(){
  var message = $('#message').val();
  var username = $('#username').val();

  var send = {
    message: message,
    username: username
  };
  sock.send(JSON.stringify(send));
}

ws.example.com的其他nginx指令

location /chat {
    proxy_pass http://0.0.0.0:5959;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

我正在添加我的模板代码,其中包括Tom的客户端js文件。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <title>Sock chat</title>
  </head>
  <body>
    <textarea id="chat-content" style="width:500px;height:300px"></textarea><br/>
    <input type="text" name="" value="" id="username" placeholder="Choose username"/>
    <input type="text" id="message" name="" value="" placeholder="Enter chat message"/>
    <input type="button" name="" value="Send" onclick="sendMessage()"/>

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.1/sockjs.min.js"></script>
    <script src="index.js" ></script>//you can see its' source above i called it Client.
  </body>
</html>

我在代理中使用了http,因为服务器已经将http重定向到https。我该如何解决我的问题?感谢

0 个答案:

没有答案