使用节点js和socket io处理响应

时间:2013-02-28 12:25:46

标签: javascript node.js javascript-events websocket

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

这可以通过http处理程序处理所有请求,然后通过socket 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);


    });
});

2 个答案:

答案 0 :(得分:2)

是肯定的。只需查看一个socket.io webpage,了解如何使用它。

答案 1 :(得分: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>