在共享主机中,有没有替代Websockets的方式可以使用?我知道node.js、socket.io和Express.js,但无法在共享主机中使用它们。因此,如果有任何可用于制作实时网站的替代方案,请告诉我。
在共享主机中,有没有替代Websockets的方式可以使用?我知道node.js、socket.io和Express.js,但无法在共享主机中使用它们。因此,如果有任何可用于制作实时网站的替代方案,请告诉我。
我认为“服务器发送事件(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();
?>
如果您在共享主机上进行实时通信,可以考虑使用像PubNub这样的托管实时网络。使用像PubNub这样的托管实时解决方案意味着您无需担心开放端口或持久进程。
这里有一个完整的hello world教程,可帮助您开始使用PubNub博客: http://www.pubnub.com/blog/php-push-api-walkthrough/
以下是一个简单的示例。
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