0
我正在使用Express和Socket.IO實現Web應用程序中的實時通知服務。客戶端可以連接到服務器,並從服務器接收發射。但是,服務器並未從客戶端接收。在服務器端事件發生時,我甚至已經在Express中設置發佈路由發送給客戶端,並且這些工作正常。使用Socket.IO Express:服務器無法接收客戶端發出的信號
客戶端代碼:
<script type="text/javascript">
var socket = io("https://{$_SERVER['HTTP_HOST']}:7076");
socket.on('message', function(data) {
alert(data.message);
});
socket.on('connected', function(data) {
if(data.success) {
socket.emit('join', {
empid: '{$_SESSION['userID']}',
rooms : [
'0{$_SESSION['MasterID']}',
'1{$_SESSION['userDivisionID']}',
'2{$_SESSION['userDistrictID']}',
'3{$_SESSION['userRegionID']}',
'4{$_SESSION['userOfficeID']}'
]
});
}
});
$(document).ready(function(){
var doc = $(document);
doc.on('click', '#join_button', function(){
socket.emit('join', {
empid: '{$_SESSION['userID']}',
rooms : [
'0{$_SESSION['MasterID']}',
'1{$_SESSION['userDivisionID']}',
'2{$_SESSION['userDistrictID']}',
'3{$_SESSION['userRegionID']}',
'4{$_SESSION['userOfficeID']}'
]
});
});
doc.on('click', '#emit_button', function() {
socket.emit('office message', {
office: 3454,
message: 'Hello'
});
});
});
</script>
<div style="padding: 32px;">
<input id="join_button" type="button" class="btn btn-primary" value="Click 2 Join" />
<input id="emit_button" type="button" class="btn btn-primary" value="Click 2 Emit" style="float:right;"/>
</div>
服務器代碼:
var app = require('express')(),
https = require('https'),
fs = require('fs'),
routes = require('./mod/routes'),
socketRoutes = require('./mod/socket/routes'),
sockets = require('./mod/socket/sockets'),
config = require('./mod/config'),
socketArray = {},
options = {
key: fs.readFileSync('4096_SSL.key').toString(),
cert: fs.readFileSync('wild.crt').toString(),
ca: fs.readFileSync('gd_bundle.crt').toString()
},
server = https.createServer(options, app);
app.use(require('body-parser').urlencoded({
extended: true
}));
/****************
* Basic Routes *
****************/
app.all('*', routes.setAccessControl);
app.get('/', routes.base);
/*--- Server Side Post Routes ---*/
app.post('/notify/:type', routes.notify);
app.get('/employees/:masterid', routes.employees);
//404 page that doesn't trigger error handling in ajax calls
app.use(routes.fallback);
//start listening on alternate https port
server.listen(7076);
//have socket.io listen to the same https port.
var io = require('socket.io')(server);
/*****************
* Socket Events *
*****************/
io.on('connection', function(socket) {
io.sockets.emit('message', {
message: 'New user Connected'
});
socket.emit('connected', {
success: 1
});
});
io.on('join', function(socket) {
console.log('subscribing');
});
io.on('office message', function(from, data){
console.log(data);
});
服務器響應連接事件就好了,並且客戶端收到「新用戶」的消息。但是,如果我點擊發出該事件的任一按鈕,則服務器上不會發生任何事情。我甚至將它綁定在連接事件的回覆中,以查看它是否是單擊問題。任何想法爲什麼服務器只是沒有響應的事件?
哇,我以前就是這樣,只是在我將應用程序移到Express時沒有移植它。我不覺得自己像個白癡。謝謝。 – Peter 2014-09-26 14:57:06
這有點難,沒有描述性的錯誤:) – Nepoxx 2014-09-26 15:04:54