2017-11-24 11 views
0

NodeJS、ExpressJS、およびルーティングコントローラを使用して簡単なREST APIを実装しました。また、REST APIと一緒に実行され、WSを使用する基本WebSocketサーバーを実装しました。NodeJS + WSアクセスで現在WSサーバインスタンスが実行中

const app = express(); 

app.use(bodyParser.json({limit: "50mb"})); 
app.use(bodyParser.urlencoded({limit: "50mb", extended: true})); 

useExpressServer(app, { 
    controllers: [ 
     UserController 
    ] 
}); 

const server = app.listen(21443, (err: Error) => { 
    console.log("listening on port 21443"); 
}); 

const wss = new WebSocket.Server({server}); 

wss.on("connection", (ws: WebSocket) => { 
    ws.on("message", (message: string) => { 
     console.log("received: %s", message); 
     ws.send(`Hello, you sent -> ${message}`); 
    }); 

    ws.send("Hi there, I am a WebSocket server"); 
}); 

私の質問は、私は私のコントローラメソッドからsendまたはbroadcastにできていますように、私は、現在実行中のWSインスタンスへのアクセスを取得する方法です。私は多くのPOSTメソッドを使用して長いプロセスを実行し、HTTP 200をクライアントに返すので、接続されたすべてのWSクライアントにsendまたはbroadcastのいずれかを送信します。

コントローラークラス内からWebSocket.Serverインスタンスにアクセスする正しい方法は何ですか?

答えて

0

接続されたクライアントのリストは、wssオブジェクト内に格納されています。

wss.clients.forEach((client) => { 
    if (client.userId === current_user_id && client.readyState === WebSocket.OPEN) { 
     // this is the socket of your current user 
    } 
}) 

これで、クライアントを何とか識別する必要があります。あなたは、接続上でこのクライアントにいくつかのIDを割り当てることによって、それを行うことができます。

wss.on('connection', async (ws, req) => { 
    // req.url is the url that user connected with 
    // use a query parameter on connection, or an authorization token by which you can identify the user 
    // so your connection url will look like 
    // http://example.com/socket?token=your_token 
    ws.userId = your_user_identifier 
    .... 
}) 

使用をブロードキャストするには:

wss.clients.forEach((client) => { 
    if (client.readyState === WebSocket.OPEN) { 
     client.send(data); 
    } 
}); 

あなたのコントローラとソケットが異なるファイルになります(と私は、彼らは確信していた場合)ソケットファイルにwssオブジェクトをエクスポートし、コントローラにインポートする必要があります。