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>