標籤:style http io os ar 使用 for strong sp
我從沒有見過比 CCLHTTPServer 更簡單的 iOS HTTP 伺服器了。你甚至不用建立任何子類即可使用它。對於大部分任務,這個小巧但強悍的伺服器能夠滿足你的需要。
它簡單到令人髮指,因此我認為光看它的首頁介紹就已經足夠了:
https://github.com/cocodelabs/CCLHTTPServer
CCLHTTPServer 是一個 iOS/OSX 下的簡單HTTP 伺服器架構。
一、用法
以下代碼建立了一個簡單的 HTTP 伺服器,監聽指定連接埠,並用指定的 CCLHTTPServerResponse類(子類)進行響應。
Objective-C:
CCLHTTPServer*server = [[CCLHTTPServer alloc] initWithInterface:nil port:8080handler:^id<CCLHTTPServerResponse>(id<CCLHTTPServerRequest>request) {
NSDictionary *headers = @{
@"Content-Type":@"text/plain; charset=utf8",
};
NSData *body = [@"Hello World"dataUsingEncoding:NSUTF8StringEncoding];
return [[CCLHTTPServerResponse alloc]initWithStatusCode:200 headers:headers body:body];
}];
Switf:
varserver:CCLHTTPServer=CCLHTTPServer(interface: nil, port: 7433, handler:
{request in
let headers =["Content-Type": "text/plain; charset=utf8"]
let body = "Hello World".dataUsingEncoding(NSUTF8StringEncoding);
returnCCLHTTPServerResponse(statusCode: 200, headers: headers, body: body)
})
CCLHTTPServerResponse 必須對傳遞給它的request 參數進行處理。request 參數是一個實現了CCLHTTPServerRequest 協議的對象,該協議封裝了各種有用的方法,你可以利用這些方法建立一個各種 response(該協議下面會詳細介紹)。
CCLHTTPServer 的目的是暴露一個用於建立HTTP 伺服器的標準 O-C 介面,見CLLHTTPServer/Interface 目錄。也就是說,別的 HTTP 伺服器也能使用這些介面,開發人員不用管某個伺服器的具體實現即可使用該介面編寫自己的架構。
二、請求 Request
request 是一個實現了 CCLHTTPServerRequest 協議的對象,該協議暴露了 HTTP 要求的基本詳細例如要求方法、路徑、HTTP 版本,headers 以及本文。
@protocol CCLHTTPServerRequest<NSObject>
- (NSString *)method;
- (NSString *)path;
- (NSString *)HTTPVersion;
- (NSDictionary *)headers;
- (NSData *)body;
@end
三、響應 Responses
你可以建立一個 response 類,也可以使用的任何已經實現了 CCLHTTPServerResponse協議的已有類。當然,絕大多數情況下,使用 CCLHTTPServerResponse 足矣。
1、返回 NSData 資料
[CCLHTTPServerResponseresponseWithStatusCode:204 headers:nil body:nil];
2、返迴文本資料
[CCLHTTPServerResponseresponseWithStatusCode:200
headers:nil
content:@"Hello World"
contentType:@"plain/text"];
3、返回 URL 編碼的名值對
這種形式如同: name=Kyle&sex=female
[CCLHTTPServerResponseformURLEncodedResponseWithStatusCode:200
headers:nil
parameters:@{@"name": @"Kyle"}];
4、返回 JSON 資料
[CCLHTTPServerResponseJSONResponseWithStatusCode:200
headers:nil
parameters:@{@"name": @"Kyle"}];
四、安裝
pod ‘CCLHTTPServer‘
【iOS開原始碼】(1):CCLHTTPServer