美文网首页
使用SocketRocket框架+php的Ratchet实现基于

使用SocketRocket框架+php的Ratchet实现基于

作者: unravelW | 来源:发表于2018-11-06 10:24 被阅读0次

正常app与服务端通信使用http协议就可以,但是如果我们遇到app与服务器频繁通信或者服务器需要向客户端推送消息时就可以使用websocket建立长连接进行通信。

我们只需要在app端和服务器上集成相应的框架,便可以建立websocket长连接进行通信。

1、app端集成SocketRocket框架

使用pod管理集成SocketRocket到项目中,并添加相应代码

#import  <SocketRocket.h>

- (void)initWebSocket {

    //init websocket

    NSString *urlStr = [NSString stringWithFormat:@"wss://localhost/wss2/phone_%@",[AccountManager sharedInstance].user.userId];

    self.webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:urlStr]];

    self.webSocket.delegate=self;

}

这里我们需要注意的是当调用[self.webSocket close]后,再次调用[self.webSocket open]时需要再次初始化self.webSocket。

当我们打开连接后,就可以使用[self.webSocket send:data]发送数据。

2、服务端集成Ratchet框架

这里我们的服务端是用php写的,php下有Ratchet框架来提供websocket服务,我们先使用composer来集成这个框架,随后建立两个php文件,并添加相应代码。

chat-server.php

<?php

use Ratchet\Server\IoServer;

use Ratchet\Http\HttpServer;

use Ratchet\WebSocket\WsServer;

use MyApp\Chat;

    require dirname(__DIR__).'/vendor/autoload.php';

    $server = IoServer::factory(

        new HttpServer(

            new WsServer(

                new Chat()

            )

        ),

        3000

    );

    $server->run();

?>

chat.php

<?php

namespace MyApp;

use Ratchet\MessageComponentInterface;

use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {

    protected $clients;

    public function __construct() {

        $this->clients = new \SplObjectStorage;

    }

    public function onOpen(ConnectionInterface $conn){

        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId}) ({$conn->httpRequest->getRequestTarget()})\n";

    }

    public function onMessage(ConnectionInterface $from, $msg) {

     }

    public function onClose(ConnectionInterface $conn) {

        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";

    }

    public function onError(ConnectionInterface $conn, \Exception $e) {

        echo "An error has occurred:{$e->getMessage()}\n";

        $conn->close();

    }

}

?>

之后我们打开终端运行php chat-server.php命令,就可以开启websocket服务了。

如果我们的web服务是https的,我们就需要使用wss协议。ratchet框架提供SecureServer类来实现wss协议。我们也可以在apache下的httpd.conf文件中添加一行代码。

ProxyPass /wss2/ ws://localhost:3000/

使wss协议先走代理转成ws协议再使用。

3、H5代码

var wsUrl = 'wss://localhost/wss2/'.concat(arr.pop());

    var ws = new WebSocket(wsUrl);

    ws.onmessage = function(event) {

      var data = event.data;

      console.log(data);

    }

相关文章

网友评论

      本文标题:使用SocketRocket框架+php的Ratchet实现基于

      本文链接:https://www.haomeiwen.com/subject/hwtexqtx.html