简体   繁体   中英

multiple browser instances with websocket capabilities in node?

Let's say I am building a social app. I want to log into multiple accounts (one per browser instance) without an user interface (all via node), and by calling all respective endpoints to log in and start chatting.

The important part is to test when an user closed the tab or logs out or leaves the group and therefore the websocket's connection closes.

If I understand you correctly. You would like to make a server-side event happen whenever a client connects or disconnects, without any html,css.... or any other user interface. You can do it like this in node :

For connection you use :

 Server.on("connection,function(ws){some stuff...})

The function that is called on connection will get the websocket that connected as parameter by default. I just use a lambda function here you can also call one that will then get the websocket as parameter.

For disconnection you put a function in the Server.on function to monitor when the client disconnected. Like this :

 Server.on("connection,function(ws){ ws.onclose = function (ws) { some stuff... } })

You can again replace the lambda function by another one. Server is in my case equal to this :

 const wsserver = require("ws").Server const server = new wsserver({ port: someport })

But it can vary. All you need to do apart from that is connect the client. I do it like this but it can vary as well.

 const ws = new WebSocket("ws://localhost:someport");

I hope this is helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM