手机WIFI传文件到局域网服务器,iOS 设备实现wifi局域网传输文件到iphone

前几天开会leader 说,测试一下iOS设备搭建局域网服务器.数据传输的各项指数.于是开始了CocoaHTTPServer的学习之路,并在网上参考了各位大佬的教程.

原理:

利用CocoaHTTPServer框架能够在iOS上建立起一个本地服务器,只要电脑/手机(iOS和Android都可以)和移动设备连入同一热点,即可使用电脑访问iOS服务器的页面,利用POST实现文件的上传。

实现:1.下载CocoaHTTPServer

2.解压后,将CocoaHTTPServer-master目录下的Core导入工程。

3.打开Samples/SimpleFileUploadServer,将其中的MyHTTPConnection类文件、web文件夹导入工程。

4.打开Vendor,将其中的CocoaAsyncSocket、CocoaLumberjack文件夹导入。

5.打开工程,打开MyHTTPConnection.m,根据标记#pragma mark multipart form data parser delegate跳转或者直接找到139行,- (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header方法,将其中filePath的值修改为iOS的某个目录,这个路径是上传的文件存储的路径,这里以Caches为例:

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

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

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

httpServer = [[HTTPServer alloc] init];

[httpServer setType:@"_http._tcp."];

// webPath是server搜寻HTML等文件的路径

NSString *webPath = [[NSBundle mainBundle] resourcePath];

[httpServer setDocumentRoot:webPath];

[httpServer setConnectionClass:[MyHTTPConnection class]];

self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

self.window.rootViewController = [[UIViewController alloc] init];

[self.window makeKeyAndVisible];

NSError *err;

if ([httpServer start:&err]) {

NSLog(@"port %hu",[httpServer listeningPort]);

}else{

NSLog(@"%@",err);

}

return YES;

}

7.运行后,在控制台打印出端口号,再通过路由器或者热点工具查询设备的内网ip,通过ip:port访问即可,如果成功.如果不知道怎么样获得IP

请看下面

.h

#import@interface CSMIPHelper : NSObject

+ (NSString *)deviceIPAdress;

@end

.m 文件

#import "CSMIPHelper.h"#include#include#include@implementation CSMIPHelper

+ (NSString *)deviceIPAdress {

NSString *address = @"an error occurred when obtaining ip address";

struct ifaddrs *interfaces = NULL;

struct ifaddrs *temp_addr = NULL;

int success = 0;

success = getifaddrs(&interfaces);

if (success == 0) { // 0 表示获取成功

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;

}

}

freeifaddrs(interfaces);

return address;

}

@end

8. 如果上传成功,就把文件上传到您的iPhone了。

总结:经过测试发现,搭建的局域网可支持上传各类型文件,上传速度和局域网信号质量有关,如果使用手机热点创建局域网,不会消耗手机流量. 个人热点的有效距离在15米左右,可同时支持多台设备连接局域网进行上传.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值