首页 > 解决方案 > 我可以使用 Unix 套接字在两个 iOS 应用程序之间进行本地通信吗

问题描述

背景:我有两个 iOS 应用程序需要在本地相互交换数据。理想的场景是应用 A 使用 URL 方案将应用 B 调用到前台,应用 A 在后台,两个应用可以相互交换多轮数据。我可以声明应用程序 A 能够在后台运行(我有正当理由这样做),因此 A 的后台执行不是问题。我不想继续在两个应用程序之间的数据交换部分使用 URL 方案,因为使用 URL 方案会打开另一个应用程序,这意味着如果有多轮数据交换,这两个应用程序将被多次打开。

另请注意,这两个 iOS 应用程序不属于同一个开发人员,因此任何依赖应用程序组共享数据的东西在这种情况下都不起作用......

目前,我找到了一个使用绑定到本地环回接口的Unix Internet 域套接字的解决方案。它在技术上是可行的,但我不知道苹果是否允许这样做?有没有更好的方法来做到这一点?

这是unix套接字的代码:

对于服务器应用程序(应用程序 A):

BOOL _listenForConnections = false;
    int listenfd = 0;
    struct sockaddr_in serv_addr;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, '0', sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(8008);
    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    _listenForConnections = true;
    listen(listenfd, 10);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"Waiting for connections...");
        while (_listenForConnections)
        {
            __block int connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
            NSLog(@"Connection accepted");
            char buffer[4096];
            bzero(buffer, 4096);
            NSString *message = @"";
            bool continueReading = true;
            do{
                recv(connfd , buffer , 4096 , 0);
                    continueReading = false;
                NSLog(@"%@", [NSString stringWithFormat: @"%@", [NSString stringWithFormat: @"Received message from client: %@%s", message, buffer]]);
            }while (continueReading);
            char* answer = "Hello World";
            write(connfd, answer, strlen(answer));
            NSLog(@"%@", [NSString stringWithFormat: @"Sent response to client"]);
        }
        NSLog(@"Now stop listening for connections");
        close(listenfd);
});

标签: iossocketsipctcpsocket

解决方案


推荐阅读