2017-08-07 88 views
0

有一個使用socket.io的服務器。當用戶連接時,它會爲其分配在服務器上創建的用戶標識,然後將其增加1,以便下一個用戶擁有不同的標識。用戶使用套接字連接時創建一個cookie。 io - 節點js

我想爲此使用cookie,以檢查他們是否先前已登錄,如果是,請使用該標識,如果不是,則使用服務器上的標識。

創建一個cookie的方法是使用

res.cookie('cookie', 'monster') 

,但我不是在那裏我會穿上它,我試圖把它的連接功能,但水庫難道不存在。如果我把它放在功能之外,我會怎樣稱呼它?這是我的代碼。這是我的服務器的開始:

//Require npm modules 
var express = require('express'); 
var http = require('http'); 
var events = require('events'); 
var io = require('socket.io'); 
var ejs = require('ejs'); 
var app = express(); 

//Set the default user Id to 1 and the default username to Guest 
exports.Server = Server = function() 
{ 
    this.userId = 1; 
    this.userName = "Guest"; 
}; 

app.set('view engine', 'ejs'); 
app.get('/game/:id', function (req, res) 
{ 
    res.render('game', {game: req.params.id}); 
}); 


Server.prototype.initialise = function(port) 
{ 
    //Create the server using the express module 
    this.server = http.createServer(app); 

    //Declare the 'public' folder and its contents public 
    app.use(express.static('public')); 

    //Listen to any incoming connections on the declared port and start using websockets 
    this.server.listen(port); 
    this.startSockets(); 
    this.em = new events(); 

    consoleLog('SERVER', 'Running on port: ' + port); 
}; 

Server.prototype.startSockets = function() 
{ 
    //When a user connects to the server on the 'game' socket 
    this.socket = io.listen(this.server); 

    this.socket.of('game').on('connection', function(user) 
     { 
      res.cookie('cookie', 'monster') 
      //Set their usedId and username 
      user.userId = this.userId; 
      user.userName = this.userName + " " + this.userId; 

      //Increment the user id by 1 so each user with get a unique id 
      this.userId++; 

      //Send a response back to the client with the assigned username and user id and initialise them 
      user.emit('connected', user.userId, user.userName); 
      this.em.emit('initialiseUser', user.userId, user.userName); 

那麼,我有res.cookie是我希望能夠讀寫餅乾,任何幫助appriciated

+0

您正在引用'res',但它是未定義的。它可能會拋出一個錯誤。 – styfle

+0

這就是我的整個問題 –

+0

你需要傳遞'res'作爲參數。你必須缺少一些代碼,因爲我看不到'initialise()'在任何地方被調用。 – styfle

回答

1

我想你在找什麼因爲express是採用的中間件模式。您可以根據需要定義許多這些中間件調用,並且它們是調用可能需要實例的其他功能的完美示波器(或針對該事件的實例)。

app.use(function (req, res, next) { 
    // call function, passing in res here 
    next(); 
}) 

參考:https://expressjs.com/en/guide/using-middleware.html

編輯:

這個答案不適合您的情況是正確的。在沒有使用套接字連接的節點/快遞服務器中,是的,您可以輕鬆地在需要範圍內的請求和響應對象的任何位置使用上述模式。

但是,一旦你設置了socket io服務器,遊戲就會改變。在套接字通信期間,不再有作用域中的明確請求和響應對象,所有事情都在套接字處理代碼和客戶端之間直接處理。所以答案是你需要以套接字的方式處理情況,而不是以一種明確的方式。

請參閱:Adding a cookie value on Socket.IO

+0

我試過這個,當我因某種原因連接時總共運行7次。我怎麼會在這裏設置用戶ID? –

+0

好的,所以你需要考慮與請求和響應的快速路由分開的套接字io連接。一旦建立了套接字連接,將其視爲與套接字處理代碼的直接連接,這意味着不會有res或req實例,但此時您不需要它們。當您執行套接字發射時,您可以發回任何您想要的數據。在另一端接收數據的代碼可以決定在客戶端看到某個類別的發射時設置一個cookie,例如代碼示例中的「connected」。 –

+0

好,那麼你說,一旦客戶端正在加載,應該檢查客戶端的Cookie ID並將ID發送到服務器中的連接功能。然後,如果該ID在服務器上的ID數組中,請使用該用戶ID登錄它們。我認爲這可能會工作不好試試 –