1

我有一个网页最初由 HTTP 提供服务的场景。单击提交后,它将向服务器发送一些数据并执行一些需要很长时间的 Web 服务。我需要快速显示响应页面,并且在 Web 服务作业完成后必须在之前加载的同一页面中显示结果。

这是否可能通过 http 处理程序处理所有请求然后通过套接字 io 传递结果来实现。

我希望写一些类似的代码。

var httpd = require('http').createServer(handler);
var io = require('socket.io').listen(httpd);
var fs = require('fs');
httpd.listen(4000);
function handler(req, res) {
    fs.readFile(__dirname + '/index.html',
        function(err, data) {
            if (err) {
                res.writeHead(500);
                return res.end('Error loading index.html');
            }
            res.writeHead(200);

            res.end(data);
        }
        );

}
io.sockets.on('connection', function (socket) {
    socket.on('clientMessage', function(content) {
       setTimeout(function () {
           socket.emit('serverMessage', "web service complete");
       }, 5000);


    });
});
4

2 回答 2

2

是的。只需查看一个socket.io 网页即可了解如何使用它的示例。

于 2013-02-28T13:09:43.177 回答
2

我为我的问题找到了解决方案,所以我将其添加为我自己问题的答案。我提到了 socket.io 聊天应用程序,它很有用,但没有完整的文档。对于某些功能,我们需要通过源代码。我使用会话来识别套接字和 http 请求以及每个客户端。我将粘贴我发现可行的代码。

 var io = require('socket.io');
    var express = require('express');
    var http = require('http');
    var fs = require('fs');
    var connect = require('connect');
    var cookie = require("cookie");
    var app = express();
    var server = http.createServer(app)
    var parseCookie = connect.utils.parseCookie;
    var parseSignedCookie = connect.utils.parseSignedCookie;
    var MemoryStore = connect.session.MemoryStore; 
    var sessionStore = new MemoryStore();


    app.configure(function () {
        app.use(express.bodyParser());
        app.use(express.cookieParser('somesuperspecialsecrethere'));
        app.use(express.session({
            key: 'express.sid',
            store: sessionStore
        }));

    });

    app.get('/', function(req, res){
        fs.readFile(__dirname + '/index.html',
            function(err, data) {
                if (err) {
                    res.writeHead(500);
                    return res.end('Error loading index.html');
                }

                res.writeHead(200);
                res.end(data);
                console.log("SessionID from http: "+req.sessionID);

    setTimeout(function () { //this is for simulating a time taking task
               var sock_id = io.sockets.sockets[req.sessionID];

            io.sockets.sockets[sock_id].emit("getmessage","my mmmmmmmmmmmmmessssssage");

        }, 5000);

            });
    });


    GLOBAL.sio = io.listen(server);
    server.listen(3000);

    sio.sockets.on('connection', function (socket) {

        var hs = socket.handshake;

        socket.on('clientMessage', function(data) {
        console.log("Message from client: "+ data.message);

        io.sockets.sockets[hs.sessionID] = socket.id;
      });

    });

    sio.set('authorization', function (data, accept) {
        if (!data.headers.cookie) {
            return accept('Session cookie required.', false);
        }

        data.cookie = cookie.parse(data.headers.cookie);

        data.cookie = parseSignedCookie(data.cookie['express.sid'], 'somesuperspecialsecrethere');

        data.sessionID = data.cookie;

        console.log('Session Id from socket: ' + data.sessionID);

        sessionStore.get(data.sessionID, function(err, session){
            if (err) {
                return accept('Error in session store.', false);
            } else if (!session) {
                return accept('Session not found.', false);
            }
            // success! we're authenticated with a known session.
            data.session = session;
            return accept(null, true);
        });



        <html>
            <head>
                <title>express WebSocket chat</title>
                <script src="http://10.3.0.52:3000/socket.io/socket.io.js"></script>
                <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>

            </head>
            <body>

                <script src="http://10.3.0.52:3000/socket.io/socket.io.js"></script>
                <script type="text/javascript">


                    var sio = io.connect('http://10.3.0.52:3000');

                    sio.socket.on('error', function (reason){
                        console.error('Unable to connect Socket.IO', reason);
                    });

                    sio.on('connect', function (){
                        console.info('successfully established a working connection ');
                    });

 sio.on('getmessage', function(data) {
        console.log(data);

        });
                </script>

                <input type="text" name="message" id="message">
                <input type="button" name="send" id="send" value="Send">
            </body>
        </html>
于 2013-03-15T13:05:43.920 回答