多个 Websocket [英] Multiple Websockets

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

问题描述

我试图在一页上使用两个 websocket.这是我的代码:

I'm trying to use two websockets on one page. This is my code:

var pageViewWs = new WebSocket("ws://localhost:9002/pageView");
var sessionWs = new WebSocket("ws://localhost:9002/session");

pageViewWs.onmessage = function (event) {
  alert("PageView");
};

sessionWs.onmessage = function (event) {
  alert("Session"); 
};

仅显示 PageView 警报.在服务器端,不向/session 发出请求,只向/pageView 发出请求.

Only the PageView alert appears. On the server side no requests are made to /session, only to /pageView.

现在,如果我切换 var pageViewWs 和 var sessionWs,则会显示会话警报而不是 PageView.这不是因为它们是警报,我已经尝试附加到正文和 div 并且我已经逐步使用 Firebug.似乎一次只能创建一个 WebSocket,尽管在 Firebug 中,pageViewWs 和 sessionWs 的属性看起来是一样的,除了它们的 url.

Now, if I switch var pageViewWs and var sessionWs around then the Session alert is shown instead of the PageView. It is not because they are alerts, I've tried appending to the body and to divs and I've stepped through using Firebug. It seems that only one WebSocket can be created at a time although in Firebug the properties for pageViewWs and sessionWs appear the same with the exception of their url.

我只在 Firefox 15.0.1 中测试过.是否存在某种 Websocket 限制,您一次只能运行一个?还是我的代码有问题?

I've only tested this in Firefox 15.0.1. Is there some sort of Websocket limitation whereby you can only run one at a time? Or is something wrong with my code?

推荐答案

我遇到了同样的问题,通过同一个端口运行多个服务.因此,我创建了一个 PHP 库来执行此操作.

I faced the same problem to run multiple services through the same port. So, I created a PHP library to do this.

托管服务提供商的一些免费计划不允许您绑定到端口或允许您绑定到一个端口.对于OpenShift Cloud Server,您只能绑定到端口 8080.因此,无法运行多个 WebSocket 服务.在这种情况下,Francium DiffSocket 很有用.

Some free plans of hosting providers don't allow you to bind to ports or allow you to bind to one port. In case of OpenShift Cloud Server, you can only bind to port 8080. So, running multiple WebSocket services is not possible. In this case, Francium DiffSocket is useful.

您可以使用名为 Francium DiffSocket.

You can run different services on the same port using a PHP library called Francium DiffSocket.

设置 Francium DiffSocket 后,您可以为使用不同的服务执行此操作:

After setting up Francium DiffSocket, you can do this for using different services :

var chatWS = new WebSocket("ws://ws.example.com:8000/?service=chat");
var gameWS = new WebSocket("ws://ws.example.com:8000/?service=game");

一个例子是这些通过单个端口运行的服务:

An example are these services which are running through a single port :

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

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