Node.js socket.io前端后端通讯简单例子

前端代码:





    



    

    后端代码:

    var express = require('express');
    var app = express();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var path = require('path');
    app.use(express.static(__dirname));
    app.get('/', function (request, response) {
        response.sendFile(path.join(__dirname, 'index.html'));
    });
    
    io.on('connection', function (socket) {
        console.log('a user connected');
        socket.on('disconnect', function () {
            console.log('user disconnected');
        });
        socket.on('message', function (message) {
            console.log('message: ' + message);
            io.emit('message', message);
        });
    });
    
    var server = http.listen(4000, function () {
        console.log('Sever is running');
    });


    你可能感兴趣的:(socket)