有没有其他替代WebSockets在共享主机中使用的方法?

7

在共享主机中,有没有替代Websockets的方式可以使用?我知道node.js、socket.io和Express.js,但无法在共享主机中使用它们。因此,如果有任何可用于制作实时网站的替代方案,请告诉我。


你最好选择购买一个VPS,它们的价格低至每月$5。 - Henrik Karlsson
获取一个VPS。由于共享主机的内部服务器组织,通常存在某些限制。 - Kanishka Ganguly
@Ineentho,您是指从办公室或家庭托管Web服务器吗?如果是的话,对我来说非常困难,因为我在巴基斯坦,那里有电力中断。所以,请告诉我是否有其他可用的东西? - user3133148
3个回答

7

我认为“服务器发送事件(Server-Sent Events)”是一种很好的替代方案,它是单向的,但我认为它在大多数情况下比Websockets更好,因为它更容易设置,不需要特殊的服务器或库,并且没有额外的协议要遵循,只需从php中使用echo,然后在javascript中使用onmessage即可。

以下是一个快速示例(来自https://www.w3schools.com/html/html5_serversentevents.asp):

Javascript代码:

var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
  document.getElementById("result").innerHTML += event.data + "<br>";
};

PHP:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

在我看来,这确实是最好的答案。被采纳的答案中提出的建议似乎不能满足原帖作者的需求。SSE 真的是解决这个问题的最佳方式。 - DoceAzedo
服务器发送事件与Apache不太兼容。 - Tyler Lazenby
在我的共享主机上,服务器没有发送任何消息。在本地主机上它可以工作。我该如何调试它? - user2342558

3

如果您在共享主机上进行实时通信,可以考虑使用像PubNub这样的托管实时网络。使用像PubNub这样的托管实时解决方案意味着您无需担心开放端口或持久进程。

这里有一个完整的hello world教程,可帮助您开始使用PubNub博客: http://www.pubnub.com/blog/php-push-api-walkthrough/

以下是一个简单的示例。

enter image description here

Let’s take a look at how developers can create channels between PHP and JavaScript. The most common usage pattern for real time applications will be explained first. A JavaScript Browser (like Firefox) will subscribe and listen for messages with PUBNUB.subscribe(). PHP will then push messages with $pubnub.publish().

PUBNUB.subscribe( { channel : 'my_test_channel' }, function(message) {
if ('some_text' in message) {
    alert(message.some_text);
}} );

The above JavaScript is fully cross browser compatible. The code will listen for messages published on ‘my_test_channel’ channel. When a message is received, the JavaScript will validate if ‘some_text‘ exists in the message object. If this attribute exists, then show an alert box!

Now use PHP to publish a message to invoke the JavaScript Alert box.

## Publish Messages To a JavaScript Browser 
$pubnub = new Pubnub( 'publish_key', 'subscribe_key' ); $pubnub->publish(array(
  'channel' => 'my_test_channel',
  'message' => array( 'some_text' => 'hello!' ) ));

This PHP code will send a message to a JavaScript Browser listening on ‘my_test_channel‘ channel. When this PHP Code executes, a JavaScript Browser will receive the PHP array and show an alert message of ‘hello!’.

http://www.pubnub.com/blog/php-push-api-walkthrough/#sthash.jI8zntnL.dpuf


3

1
这句话的意思是,Rachet能否在共享托管账户中运行? - Nancy Moore
你提出的选项是基于独立服务器的。 - Krishnan KK
如果您拥有ssh访问权限,您可以使用websocketd。它易于使用、快速实现且免费。 - user2036944

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接