socket.io与ssl无法正常工作

时间:2017-06-11 10:02:01

标签: node.js ssl socket.io

我使用socket.io模块为websocket服务器提供了一个简单的node.js代码,但我无法使其工作。服务器运行时没有错误,但是当尝试从浏览器连接时,我收到“SOCKET错误:{”isTrusted“:true}”错误(我没有使用自签名证书,但经过测试且受浏览器信任的Symantec证书) 。
这是我的代码:

var fs = require( 'fs' ) ;
var app = require('express')();
var https  = require('https');
var server = https.createServer({    
    key: fs.readFileSync('cert.key'),
    cert: fs.readFileSync('cert.cer'),
},app);
server.listen(50100);
var io = require('socket.io').listen(server,{pingTimeout: 7000, pingInterval: 10000});
io.sockets.on('connection',function (socket) {
    console.log('new connection'); 
});

在客户端我使用的是标准的java脚本“var WS = new WebSocket(wsUri);”而wsUri是“wss:// siteaddress:50100”。
我尝试使用“ws”节点模块的代码,它似乎工作正常,但“ws”模块没有我需要的所有方法(除非我遗漏了一些东西 - 我需要能够将消息发送到选定的套接字或所有套接字在一起并在套接字连接上从客户端发送一些信息。) 我已经尝试了node.js, socket.io with SSL中的所有建议,但它们都没有为我工作 尝试通过DEBUG = * node myapp进行调试 - 这是我在日志中得到的内容:

express:application set "x-powered-by" to true +0ms
express:application set "etag" to 'weak' +7ms
express:application set "etag fn" to [Function: wetag] +2ms
express:application set "env" to 'development' +1ms
express:application set "query parser" to 'extended' +0ms
express:application set "query parser fn" to [Function: parseExtendedQueryString] +1ms
express:application set "subdomain offset" to 2 +0ms
express:application set "trust proxy" to false +1ms
express:application set "trust proxy fn" to [Function: trustNone] +1ms
express:application booting in development mode +2ms
express:application set "view" to [Function: View] +1ms
express:application set "views" to '/opt/bitnami/apache2/wm/node/views' +0ms
express:application set "jsonp callback name" to 'callback' +1ms
socket.io:server initializing namespace / +145ms
socket.io-parser encoding packet {"type":0,"nsp":"/"} +1ms
socket.io-parser encoded {"type":0,"nsp":"/"} as 0 +1ms
socket.io:server creating engine.io instance with opts {"pingTimeout":7000,"pingInterval":10000,"path":"/socket.io","initialPacket":["0"]} +0ms
socket.io:server attaching client serving req handler +10ms

当客户端尝试连接到websocket时,日志中没有任何内容 任何人都可以指出我正确的方向吗? 感谢。

2 个答案:

答案 0 :(得分:0)

服务器端:

`var express = require('express');
var app = express();
var server = app.listen(8080);
var io = require('socket.io').listen(server);`

客户方:

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>

var mySocket = io.connect('localhost:8080', {transports: 
 ['websocket'], reconnection: false,secure:false}); 

mySocket.on('connect', function () {
    mySocket.sendBuffer=[]
    console.log('Connected!');
});  

如果您的浏览器隐藏connected表示已建立连接

答案 1 :(得分:0)

尝试添加传输和来源与相应的端口

io.set('transports', ['websocket']); io.set('origins', 'YOUR_ORIGIN:*');之后

添加:

sed

检查您的规则是否已在apache或nginx上正确设置,以便您拥有wss。