美文网首页其它技术点iOS 技术精选集网络
利用CocoaHttpServer搭建手机本地服务器

利用CocoaHttpServer搭建手机本地服务器

作者: 辰牧殇 | 来源:发表于2017-04-01 18:00 被阅读2716次

缘起

今天用暴风影音看视频,然后发现它有个功能,wifi传片,感觉挺有意思,然后就上网查了下相关内容。

原理

使用CocoaHTTPServer框架,在iOS端建立一个本地服务器,只要电脑和手机连入同一热点或者说网络,就可以实现通过电脑浏览器访问iOS服务器的页面,利用POST实现文件的上传。

实现

1.下载CocoaHTTPServer

2.导入CocoaHTTPServer-master目录下的Core文件夹

3.导入Samples/SimpleFileUploadServer目录下的MyHTTPConnection类文件和web文件夹

导入web文件夹的时候,一定要使用真实的目录,而不是xcode的虚拟目录


web文件夹导入.png

4.导入Vendor目录下的CocoaAsyncSocketCocoaLumberjack文件夹

5.打开MyHTTPConnection.m文件,根据标记 #pragma mark multipart form data parser delegate 跳转或者直接找到139行的 *- (void) processStartOfPartWithHeader:(MultipartMessageHeader ) header 方法,把第151行的uploadDirPath改为

NSString *uploadDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

这个路径是上传文件的存储路径

6.在适当的地方配置server启动。这里以AppDelegate为例

#import "AppDelegate.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "MyHTTPConnection.h"

@interface AppDelegate ()
@property (nonatomic, strong) HTTPServer * httpServer;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    _httpServer = [[HTTPServer alloc] init];
    [_httpServer setPort:1234];
    [_httpServer setType:@"_http._tcp."];
    // webPath是server搜寻HTML等文件的路径
    NSString * webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"web"];
    [_httpServer setDocumentRoot:webPath];
    [_httpServer setConnectionClass:[MyHTTPConnection class]];
    NSError *err;
    if ([_httpServer start:&err]) {
        NSLog(@"port %hu",[_httpServer listeningPort]);
    }else{
        NSLog(@"%@",err);
    }
    NSString *ipStr = [self getIpAddresses];
    NSLog(@"ip地址 %@", ipStr);
    
    return YES;
}

- (NSString *)getIpAddresses{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

7.运行后,控制台会打印出端口号和ip,在电脑端浏览器里输入ip+端口号访问即可,如果成功的话会看到如下界面:

访问成功.png

8.如果上传成功,网页上会出现上传的文件名,可以在沙盒里验证文件是否上传成功

相关文章

网友评论

  • 8108b3f1e59f:我试了,在手机上开启服务器,用电脑无法访问,同一个wifi信号下,这是为什么
    83096bc6ec73:文中的Demo引用的web文件夹是蓝色的,如果你的文件夹是黄色的就需要改成NSString * webPath = [[NSBundle mainBundle] resourcePath];
    83096bc6ec73:Demo有个设置路径为web的地方,你把web文件夹拖入工程,设置 NSString * webPath = [[NSBundle mainBundle] resourcePath];为这个就可以访问了
    20adb1ed827d:这个可能是iOS9之后只允许HTTPS请求的问题,你改一下设置允许访问HTTP请求试试
  • 赵熊猫:你好,按照你给的DEMO,运行后发现获取端口这步出错,报错内容为:Error Domain=NSPOSIXErrorDomain Code=48 "Address already in use",地址已在使用,这个你是怎么处理的,真机测试
    赵熊猫:@Geselle_Joy 好的谢谢!
    辰牧殇:额,我没有遇到过啊
  • 白羊的羊:Undefined symbols for architecture armv7:
    "_OBJC_CLASS_$_HTTPServer", referenced from:
    objc-class-ref in AppDelegate.o
    ld: symbol(s) not found for architecture armv7
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    提示这个错误,大哥可以帮忙下吗?
    辰牧殇:@白羊的羊 这个必须要真机测试啊
    白羊的羊:@Geselle_Joy 都有的 现在模拟器 64 7 都不可以运行
    辰牧殇:@白羊的羊 Build Settings > Architectures > Valid Architectures 里面是否包含 armv7?
  • 雨影:app端只能监听沙盒变动才能知道收没收到文件么?没有回调么
    辰牧殇:@雨影 哦哦,学习了
    雨影:@Geselle_Joy 可以,我找到了,就是设置保存路径的那个方法
    辰牧殇:@雨影 我觉得应该是不行的吧,因为你无法监听浏览器端的操作来调取回调啊~

本文标题:利用CocoaHttpServer搭建手机本地服务器

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