简体   繁体   English

节点中具有 websocket 功能的多个浏览器实例?

[英]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.重要的部分是测试用户何时关闭选项卡或注销或离开组,从而关闭 websocket 的连接。

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.您希望在客户端连接或断开连接时发生服务器端事件,而无需任何 html、css .... 或任何其他用户界面。 You can do it like this in node :您可以在 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.连接时调用的函数会默认获取连接的 websocket 作为参数。 I just use a lambda function here you can also call one that will then get the websocket as parameter.我只是在这里使用了一个 lambda 函数,你也可以调用一个,然后将 websocket 作为参数。

For disconnection you put a function in the Server.on function to monitor when the client disconnected.对于断开连接,您在 Server.on 函数中放置了一个函数来监视客户端何时断开连接。 Like this :像这样 :

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

You can again replace the lambda function by another one.您可以再次将 lambda 函数替换为另一个函数。 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.我希望这是有帮助的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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