iOS

【iOS篇】使用websocket搭建本地服务器

2018-06-05  本文已影响22人  Geeks_Chen

1、移动端何时需要搭建本地服务器?

当移动端与web端需要很强很即时的数据交互时,服务端只需要一个结果的时候,在移动端搭建本地服务器,然后让移动端与web端交互,完成一系列动作,把结果告诉服务端,实际应用场景:积分墙。

2、如何在移动端搭建本地服务器?

#pragma mark -- 开启本地服务
-(void)openServer{
    
    self.http = [[RoutingHTTPServer alloc] init];
    // Set a default Server header in the form of YourApp/1.0
    NSDictionary *bundleInfo = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [bundleInfo objectForKey:@"CFBundleShortVersionString"];
    if (!appVersion) {
        appVersion = [bundleInfo objectForKey:@"CFBundleVersion"];
    }
    NSString *serverHeader = [NSString stringWithFormat:@"%@/%@",
                              [bundleInfo objectForKey:@"CFBundleName"],
                              appVersion];
    [self.http setDefaultHeader:@"Server" value:serverHeader];
    [self.http setDefaultHeader:@"Content-Type" value:@"text/plain"];
    
    [self.http setPort:55433];
    [self.http setDocumentRoot:[@"~/Sites" stringByExpandingTildeInPath]];
    
    [self setupRoutes];

    NSError *error;
    if ([self.http start:&error]) {
        NSLog(@"开启成功了");
    }
}

3、如何设置路由,与web交互?

#pragma mark -- 配置路由
- (void)setupRoutes {
    
    [self.http post:@"/" withBlock:^(RouteRequest *request, RouteResponse *response) {
        
        [response setHeader:@"Access-Control-Allow-Origin" value:@"*"];

        //请求参数
        NSDictionary *dicJson=[NSJSONSerialization JSONObjectWithData:[request body] options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"%@",dicJson);
        
        if ([dicJson[@"type"] isEqualToString:@"check"]) {
    
            //响应
            [response respondWithString:dicJson[@"userId"]];
        }

    }];
    
}

4、如何保持移动端后台不被kill?

-(void)applicationDidEnterBackground:(UIApplication *)application{
    
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    
}
-(void)applicationWillEnterForeground:(UIApplication *)application {
    
    [[UIApplication sharedApplication] endBackgroundTask:UIBackgroundTaskInvalid];
    
}

5、web代码


需要web基础哦.png

6、效果展示


0F91BC1C5EB1FD4F23B6534FC90BF92E.png 5ED0229C57E8755DBE09B40448D810A2.png

5、细节技术点欢迎私聊!

结束语:
本人做了一款app,在这推广一下,希望各路大神下载体验,顺便五星好评,小弟不胜感激。下载链接

达人赚.png
上一篇下一篇

猜你喜欢

热点阅读