简体   繁体   中英

Express with Socket.IO: Server doesn't receive emits from client

I am using Express and Socket.IO for a real-time notification service in a web app. The client can connect to the server, and receive emits from the server. The server, however, isn't receiving emits from the client. I have even set up post routes in Express to send emits to the client when a server side event occurs, and these work.

Client Code:

<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>

The Server Code:

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);
});

The server is responding to the connection event just fine, and the client is receiving the "new user" message. However, if I click on either of the buttons that emit the event, nothing happens on the server. I even bound it inside the reply of the connection event to see if it was a clicking issue. Any ideas why the server just isn't responding to the events?

Socket events have to be bound to the socket itself, not IO. Try something like this:

io.on("connection", onSocketConnection);

function onSocketConnection(socket) {
    io.sockets.emit('message', { messages: 'New user Connected' });
    socket.emit('connected' { success: 1 });

    socket.on('join', onClientJoined);
};

function onClientJoined(data) {
    console.log('subscribing');
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM