其实就是MVC模式,视图在在线、离线时可以共用,控制器在在线时是由服务器端实现的,而离线时则是由本地Obj-C代码实现。具体实现方式为采用Mongoose实现。
代码为:
mongoose.h
mongoose.c
附件
http://files.cnblogs.com/files/lohcve/Mongoose.zip
调用方式:
HttpServer.h
1 // 2 // NSObject+HttpServer.h 3 // sxypt 4 // 5 // Created by 李 泽波 on 13-1-9. 6 // Copyright (c) 2013年 xxx有限公司. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 #import "mongoose.h" 11 12 @interface HttpServer : NSObject 13 { 14 struct mg_context *MG_CTX;//http server 15 } 16 17 @property struct mg_context *MG_CTX; 18 19 - (void)http_server_start; 20 - (void)http_server_stop; 21 - (void)test_http_server; 22 23 @end
HttpServer.m
1 // 2 // NSObject+HttpServer.m 3 // sxypt 4 // 5 // Created by 李 泽波 on 13-1-9. 6 // Copyright (c) 2013年 xxx有限公司. All rights reserved. 7 // 8 9 #import "HttpServer.h" 10 #import "Constant.h" 11 12 @implementation HttpServer 13 14 @synthesize MG_CTX; 15 16 - (id) initHttpServer 17 { 18 self = [super init]; 19 if(self){ 20 21 } 22 return self; 23 } 24 25 - (void)http_server_start 26 { 27 NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], OfflineWebRootPath]; 28 char *rootPath = (char *)[path UTF8String]; 29 char *serverPort = (char *)[OfflineWebServerPort UTF8String]; 30 const char *options[] = { 31 "document_root", rootPath, 32 "listening_ports", serverPort, 33 NULL 34 }; 35 self.MG_CTX = mg_start(&callback, NULL, options); 36 NSLog(@"http server start at port: %@", OfflineWebServerPort); 37 } 38 39 - (void)http_server_stop 40 { 41 mg_stop(self.MG_CTX); 42 NSLog(@"http server stoped"); 43 } 44 45 - (void)test_http_server 46 { 47 NSString *urlString = [NSString stringWithFormat:@"%@:%@%@", OfflineWebServer, OfflineWebServerPort, @"/index.html"]; 48 NSURL *url = [NSURL URLWithString:urlString]; 49 NSString *response = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 50 NSLog(@"%@", response); 51 } 52 53 void *callback(enum mg_event event, struct mg_connection *conn) 54 { 55 const struct mg_request_info *request_info = mg_get_request_info(conn); 56 57 if (event == MG_NEW_REQUEST) { 58 char content[1024]; 59 int content_length = snprintf(content, sizeof(content), 60 "Hello from mongoose! Remote port: %d", 61 request_info->remote_port); 62 mg_printf(conn, 63 "HTTP/1.1 200 OK\r\n" 64 "Content-Type: text/plain\r\n" 65 "Content-Length: %d\r\n" // Always set Content-Length 66 "\r\n" 67 "%s", 68 content_length, content); 69 // Mark as processed 70 return ""; 71 } else { 72 return NULL; 73 } 74 } 75 76 @end
时间: 2024-10-10 14:22:39