建立WebSocket连接,onopen永远不会运行

时间:2017-09-13 21:51:32

标签: javascript node.js websocket

我正在尝试学习WebSockets,我在Node中创建了一个websocket服务器,现在正在开发浏览器实现。我已经测试了服务器的工作原理并使用名为Smart WebSocket Client的chrome扩展来响应我想要的方式。

当我按下按钮时,浏览器中的控制台显示Button pressed!,当我结束节点进程时Connection lost! (1000),但从未说过Connection Established!

编辑:客户端代码在使用HTTPS保护的站点上运行,并且服务于HSTS标头,而服务器代码(当前但不会继续)在localhost上正常运行HTTP,如果有任何问题。

服务器代码:

const websock = require('./node_modules/ws');
const HashMap = require('./node_modules/hashmap');
const jsonparse = require('./node_modules/jsonparse');
const randomstring = require('./node_modules/randomstring');

class Session {
    constructor(server) {
        this.server = server;
        this.clients = [];
    }
}

var connections = new HashMap();
const json = new jsonparse();

const wss = new websock.Server({ port: 36245 });

process.on('SIGINT',function () {
    console.log("Recieved SIGINT, stopping gracefully...");
    wss.clients.forEach(function (ws) {
        console.log("-Ended connection with "+ws.upgradeReq.socket.remoteAddress+" (1001)");
        ws.closeReasonCode = 1001;
        ws.close();
    });
    process.exit(1);
});

wss.on('connection',function connection(ws,conn) {
   console.log("+Recieved connection from "+ws._socket.remoteAddress);
   ws.upgradeReq = conn;
   ws.hasHandshook = false;
   ws.onmessage = function message(msg) {
       var message;
       try {
           message = JSON.parse(msg.data);
       } catch (ex) {
           ws.send("{\"e\":\"Invalid json.\"}");
           return;
       }
       if (!ws.hasHandshook) {
           ws.hasHandshook = true;
           if (message.type === "client") {
               //ensure code was provided and has a room
               if (typeof message.code === 'undefined' || !connections.has(message.code)) {
                   ws.send("{\"e\":\"Invalid game code.\"}");
                   ws.closeReasonCode = 4001;
                   ws.closeDescription = "Invalid game code.";
                   console.log("-Ended connection with "+ws._socket.remoteAddress+ " (4001)");
                   ws.close();
               }
               if (typeof message.name === 'undefined') {
                   //TODO error out, no player name provided
               }
               //attach client to game session
               ws.clientType = "client";
               ws.gameCode = message.code;
               ws.playerName =
               connections.get(message.code).clients.add(ws);
               ws.send("{\"joingame\":\"true\"}");
           } else {
               ws.send("{\"e\":\"Invalid type provided on handshake message.\"}");
               ws.closeReasonCode = 4000;
               ws.closeDescription = "Invalid type provided on handshake message.";
               console.log("-Ended connection with "+ws._socket.remoteAddress+" (4000)");
               ws.close();
           }
       }
   };
   ws.onclose = function close() {
       console.log("-Ended connection with "+ws.upgradeReq.socket.remoteAddress+" (Client Closed)");
   }
});

客户端代码,只需按下页面上的按钮即可成功运行:

function DoJoinGame () {
    console.log("Button pressed!");
    gameCode = document.getElementById('base-gameCode').value.toUpperCase();
    playerName = document.getElementById('base-playerName').value;
    var ws = new WebSocket("ws://localhost:36245");
    ws.onopen = function (event) {
        console.log("Connection Established!");
        ws.send("{\"type\":\"client\",\"code\":\""+gameCode+"\",\"name\":\""+playerName+"\"");
    };
    ws.onmessage = function (msg) {
        let message = JSON.parse(msg.data);
        if (message.joingame) { //if this is a "client added to session" message, set display: none; on the codeEntry div
            document.getElementById('codeEntry').style.display = "none";
        }
        //TODO handle message
    };
    ws.onclose = function (evt) {
        console.log("Connection lost! ("+evt.code+":"+evt.reason+")");
    };
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

问题已解决。我试图从安全的起源和chrome& amp;连接到非安全的websocket服务器。合。不是粉丝。