我会使用以下组件:
我不知道您可以在 android 端使用什么来订阅网络服务服务器。
代码相当简单,这是我在项目中使用的示例。
网络套接字服务器:
composer.json
{
"autoload": {
"psr-0": {
"MyApp": "src"
}
},
"require": {
"cboden/ratchet": "0.3.*",
"react/zmq": "0.2.*|0.3.*"
}
}
push-server.php
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$pusher = new MyApp\Pusher;
// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
// I assume the codeigniter installation and this server
// will be on the same host, hence 127.0.0.1
$pull->bind('tcp://127.0.0.1:5555');
$pull->on('message', array($pusher, 'onMessage'));
// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8081, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer(
new Ratchet\Wamp\WampServer(
$pusher
)
)
), $webSock
);
$loop->run();
然后在codeigniter中你可以使用以下方式发送消息:
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'pusher');
$zmq_srv = 'your.domain.com:5555';
$socket->connect("tcp://" . $zmq_srv);
$messageContent = array(
'user' => 'username',
'type' => 'success',
'message' => 'Hi this is a test message.',
);
$socket->send(json_encode($messageContent));
我在上面使用它来向特定用户发送消息,但是如果您创建一个所有用户都连接到的新频道,那么他们都会收到一条消息。
我的基于 Web 的应用程序在视图中使用 http://autobahn.ws/js/ 来订阅 Web-socket 提要。我看到它也有 android 实现,但我从未尝试过:http://autobahn.ws/android/
这是我的一个观点的示例代码,以防它对您有用:
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
var conn = new ab.Session('ws://your.domain.com:8081',
function () {
// Subscribe to the "username" channel
// For each user this would be their own channel to receive notifications
// for their own events, like successful file generation..
// file upload, etc...
conn.subscribe('username', function (topic, data) {
$.simplyToast(data.message, type = data.type, delay = 8000);
});
// Subscribe to "system" channel.
//In my app all users are subscribed to this one to receive system-wide
// notifications.
conn.subscribe('system', function (topic, data) {
$.simplyToast(data.message, type = data.type, delay = 8000);
});
},
function () {
console.warn('WebSocket connection closed');
},
{'skipSubprotocolCheck': true}
);
</script>