2017-12-01 12 views
0

私はexpressを使用して自分のサイト(すなわち、express mysite)を生成します。私は自分のサイトにsocket.ioサポートを追加します。しかし、私のsocket.ioクライアントがサーバに接続しようとすると、サーバは '接続'イベント(.on( 'connection'、function(socket)...)を受信し続けていることがわかりました。socket.ioはnode.jsサーバーで動作しません(特急付き)

私のクライアント

var app = require('../app'); 
var debug = require('debug')('mysite:server'); 
var http = require('http'); 
var https= require('https'); 
var fs = require('fs'); 


//Get port from environment and store in Express. 
var port = normalizePort(process.env.PORT || '3000'); 
app.set('port', port); 
app.set('httpsport', 443); 

//Create HTTP server. 
var options = { 
    key: fs.readFileSync('.\file.pem'), 
    cert: fs.readFileSync('.\file.crt') 
}; 

var server = http.createServer(app); 
var httpsServer = https.createServer(options, app).listen(app.get('httpsport')); 

//Listen on provided port, on all network interfaces. 
server.listen(port); 
server.on('error', onError); 
server.on('listening', onListening); 

//Normalize a port into a number, string, or false. 
function normalizePort(val) { 
    var port = parseInt(val, 10); 

    if (isNaN(port)) { 
     // named pipe 
     return val; 
    } 

    if (port >= 0) { 
     // port number 
     return port; 
    } 
    return false; 
} 

//Event listener for HTTP server "error" event. 
function onError(error) { 
    .......... 
} 
//Event listener for HTTP server "listening" event. 
function onListening() { 
    var addr = server.address(); 
    var bind = typeof addr === 'string' 
    ? 'pipe ' + addr 
    : 'port ' + addr.port; 
    debug('Listening on ' + bind); 
} 

//socket.io 
var io = require('socket.io')(httpsServer); 

io.on('connection', function(socket) {  
    //keep printing 'new connection' string in console 
    console.log('new connection'); 
    //client doesn't receive this message 
    socket.emit('message', {'message': 'hello world'}); 
}); 

私の/ binに/ WWWで:?

<html> 
    <head> 
     <script src="https://cdn.socket.io/socket.io-1.0.0.js"></script> 
     <script src="https://code.jquery.com/jquery-3.2.1.min.js" 
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
      crossorigin="anonymous"></script> 
    </head> 
    <body> 
     <script> 
      var URL_SERVER = 'https://localhost:443'; 
      var socket = io.connect(URL_SERVER); 

      socket.on('message', function(data) { 
      $('#message').text(data.message); 
      }); 
     </script> 
     <div id="message">Message</div> 
     </body> 
    </html>  

どんな提案

答えて

1

あなたはsocket.ioの非常に古いバージョン(1.0.0)を参照していますあなたのクライアントの中でどのversiサーバー上で使用しているsocket.ioの上にありますが、理想的にはクライアントとサーバーは一致している必要があります。

socket.ioは、サーバの/socket.io/socket.io.jsパスに対応するクライアントスクリプトを提供するか、CDNの新しいバージョンを使用できます。 1.xのブランチ(1.7.4)から最新バージョンと2.xのブランチから最新バージョン(2.0.4)の両方で私のために予想されるようにあなたのコードが実行さ

https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.4/socket.io.js https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js

+0

これはsocket.ioの真実ですので、この問題が発生します。どうもありがとう!あなたは私の日を救う! – jones321

関連する問題