使用多个websocket连接 [英] Using multiple websocket connections

查看:615
本文介绍了使用多个websocket连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,每个月都有数千次访问,而且这个网站还在不断增长. 我正在向我的网站添加可交互的新功能.

I have a site that has few thousands visits every month and its growing. I am adding new functionalities to my web that are interactive.

现在我正在处理问题,我应该为所有功能使用一个websocket连接还是为我的应用程序的每个交互功能创建新的websocket连接?

Now i am dealing with question, should i use one websocket connection for all functions or should i create new websocket connection for every interactive function of my app?

我正在考虑性能问题.创建websocket意味着我必须将连接保存在服务器上.但是,一个用户的多个连接=如果我为每种功能创建新的连接,则我必须保存的连接量要大得多.

I am thinking about performance issues. Creating websocket means i have to save the connection on server. But multiple connection for one user = the amount of connection i have to save is much larger if i create new connection for every functionality.

如何处理此问题的正确方法是什么?

What is the riht way how to deal with this?

推荐答案

我应该将一个websocket连接用于所有功能还是应该 为我的每个交互功能创建新的websocket连接 应用程序?

should i use one websocket connection for all functions or should i create new websocket connection for every interactive function of my app?

您应该只有一个websocket连接,没有理由使用多个websocket.

You should have only one websocket connection, there is no reason to use multiple websockets.

根据我的个人经验:

最好的设计是使用REST API处理来自客户端的操作,并仅将Websocket用于通知.使用REST可以为您管理解析.

Best design would be to use a REST API to handle actions comming from client and use Websocket only for notifications. using REST would manage the parsing for you.

无论如何,如果您希望所有应用程序都通过websocket协议进行通信,则可以通过套接字发送类似

Anyway, if you want all your app to communicate through websocket protocol, you can send through the socket something like

msg = {
  "action": "fly",
   "data": "plane"
}

然后使用switch case语句在服务器端对其进行处理:

Then handle it in your server side using a switch case statement:

switch(msg.action){
case 'fly': 
serverCommand.fly(msg.data);
break;
// other statements
}

或者您甚至可以做(不需要解析):

Or you can even do (no parsing needed):

serverCommand[msg.action](msg.data);

我想说的是:您无需打开多个websocket即可解决性能问题.

What I want to say is: you don't need to open multiple websockets to solve performance issues.

通过为同一个客户端打开多个websocket,您的代码将难以维护,并且您将丢失 DRY 原则.

By opening multiple websocket for same client your code will be hardly maintainable and you will lost the DRY principle.

看看那个答案,它不建议打开多个插座.

Take a look at that answer, which not recommend to open multiple sockets.

答案令人厌恶,在这种情况下,您可能想为同一个客户端打开多个websocket(请注意,它说用例是非共有)

And this answer which enumarate all the case where you may want to open multiple websockets for same client (pay attention, that it says that uses case are not commons)

这篇关于使用多个websocket连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆