2015-08-19 49 views
1

在我的socket.io/express應用程序中,我希望能夠向localhost發送GET請求:3000/send併發出消息然而到所有打開的連接,此代碼似乎並不奏效:在http get request(Express.js)上發送socket.io消息

var LISTENING_PORT = 1234; 

var app = require('express')(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 

//Example users 
app.get('/messages', function(req, res){ 
    res.sendFile(__dirname + '/messages.html'); 
}); 

//Basket Reservation Namespace 
var basket_reservation = io 
    .on('connection', function(socket){ 
    socket.on('message', function(message){ 
     console.log('Received connection from user: ' + message); 
     socket.emit('message', 'Connection started.'); 
    }); 

    app.get('/send', function(req, res){ 
     console.log('sending message to all'); 
     socket.emit('message', 'Message from GET /send'); 
     res.send('Message sent.'); 
    }); 
    }); 

http.listen(LISTENING_PORT, function(){ 
    console.log('listening on *:' + LISTENING_PORT); 
}); 

具體行socket.emit(「消息」,「從GET /發送消息」);不起作用。它上面和下面的行會被調用。

下面是客戶端:

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> 
<script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
<script type="text/javascript"> 
    var socket = io('http://localhost:1234/'); 
    socket.emit('message', 'hello'); 
    socket.on('message', function(msg){ 
    $('#messages').append($('<li>').text(msg)); 
    }); 
</script> 

<h1>User #1</h1> 


<ul id="messages"></ul> 

回答

0

我覺得你的代碼將失敗,因爲你是在io.on('connection')異步宣佈它來應對/send路線。

我建議宣佈這個io.on('connection')之外 - 我還沒有遇到我的代碼 - 所以不知道是否會運行:

//Basket Reservation Namespace 
var basket_reservation = io 
    .on('connection', function(socket){ 
    socket.on('message', function(message){ 
    console.log('Received connection from user: ' + message); 
    socket.emit('message', 'Connection started.'); 
}); 

// Helper to send message (it uses closure to keep a reference to the io connetion - which is stored in basket_reservation in your code) 
var sendMessage = function (msg) { 
    if (basket_reservation && basket_reservation.connected) { 
    console.log('sending message to all'); 
    basket_reservation.emit('message', 'Message from GET /send'); 
    } 
}; 

// Broadcast message 
app.get('/send', function(req, res){ 
    sendMessage(req.body.data); 
    res.send('Message sent.'); 
});