2015-01-10 2 views
7

私は*ここエクスプレス4.幅socket.IO 1の使用例を見つけましたが完璧に動作Everyting linkSocketIo.use(function(socket、next)) - 次はどこに行きますか?

です。しかし、コードがあります:

io.use(function(socket, next) { 
try { 
    var data = socket.handshake || socket.request; 
    if (! data.headers.cookie) { 
     return next(new Error('Missing cookie headers')); 
    } 
    console.log('cookie header (%s)', JSON.stringify(data.headers.cookie)); 
    var cookies = cookie.parse(data.headers.cookie); 
    console.log('cookies parsed (%s)', JSON.stringify(cookies)); 
    if (! cookies[COOKIE_NAME]) { 
     return next(new Error('Missing cookie ' + COOKIE_NAME)); 
    } 
    var sid = cookieParser.signedCookie(cookies[COOKIE_NAME], COOKIE_SECRET); 
    if (! sid) { 
     return next(new Error('Cookie signature is not valid')); 
    } 
    console.log('session ID (%s)', sid); 
    data.sid = sid; 
    sessionStore.get(sid, function(err, session) { 
     if (err) return next(err); 
     if (! session) return next(new Error('session not found')); 
     data.session = session; 
     next(); 
    }); 
} catch (err) { 
    console.error(err.stack); 
    next(new Error('Internal server error')); 
} 
}); 

にエラーが発生した場合、それはnextに渡すようにします。しかし、次はどこに行くの? try、catchせずにこのエラーを処理する方法。

// something here 
// And this is callback function which accepts next with err 
functin(err, anythingHere){ 
    if err 
     throw err; 
    else 
     // some code here 
} 

答えて

16

それはクライアントに行く:私はこの次は急行のように受信された場合に処理を意味します。

http://socket.io/docs/server-api/#namespace#use(fn:function):namespace

var io = require('socket.io')(); 
io.use(function(socket, next){ 
    if (socket.request.headers.cookie) return next(); 
    next(new Error('Authentication error')); 
}); 

コールバックをミドルウェアに渡されたエラーは、クライアントに特別なerrorパケットとして送信されます。

それに続くミドルウェアは呼び出されないことに注意してください。

そのようにあなたがして処理することができ、クライアント側では

socket.on('error', function(err){ 
    // do something with err 
}); 
+0

はあなたが助け、あなたの先生に感謝 – onar

関連する問題