棘轮websocket onopen事件未触发,但相同的代码正在服务器上运行

时间:2018-09-03 16:36:12

标签: javascript php nginx websocket ratchet

相同的代码在服务器上工作,但不在本地。尽管addEventListener会添加open事件,但不会触发onopen事件。我的本地服务器和实时服务器都是nginx。本地和实时php版本均为php7-fpm。唯一的区别是我的服务器配置为https,但是我的本地是http。

我的JavaScript代码:

'use strict';
var servers = {
    iceServers: [
        {urls: 'stun:stun.l.google.com:19302'}
    ]
};

var myPC;
var awaitingResponse;
var streamConstraints;
var myMediaStream;

const room = getRoom();
//const wsChat = new WebSocket("wss://localhost/websocket"); //this is for server which is HTTPS
const wsChat = new WebSocket("ws://localhost:8090");//localhost which is HTTP

wsChat.addEventListener('open', function (event) {
    console.log('open event listener');//getting this on console
});

wsChat.addEventListener('message', function (event) {
    console.log('Message event listener');
});

window.addEventListener('load', function(){    
    console.log(wsChat);
    
    wsChat.onopen = function(event){
        alert('connected'); //not getting this alert
        wsChat.send(JSON.stringify({
            action: 'subscribe',
            room: room
        }));
        showSnackBar("Connected to the chat server!", 5000);
    };
    wsChat.onerror = function(event){
        showSnackBar("Unable to connect to the chat server! Kindly refresh", 10000);
    };    
    wsChat.onmessage = function(e){
        var data = JSON.parse(e.data);
        console.log(data);
        
        if(data.room === room){
            switch(data.action){
                .....
            }  
        }
    };
});

我的服务器和本地的nginx配置。

服务器:mysite.conf

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
upstream websocket {
    server 127.0.0.1:8090;
}
......
location = /websocket{
    proxy_redirect off;

    proxy_pass http://websocket;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 3600;
  }

此配置在我的实时站点上正常工作。

本地nginx conf:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
upstream websocket {
    server 127.0.0.1:8090;
}
......
location = /websocket {
    proxy_redirect off;

    proxy_pass http://websocket;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_read_timeout 3600;
}

我在本地控制台上得到的响应。

enter image description here

没有任何线索。

0 个答案:

没有答案