CocoaHttpserver初识

支淮晨
2023-12-01

源码地址:CocoaHttpServer

Readme
CocoaHTTPServer is a small, lightweight, embeddable HTTP server for Mac OS X or iOS applications.

Sometimes developers need an embedded HTTP server in their app. Perhaps it’s a server application with remote monitoring. Or perhaps it’s a desktop application using HTTP for the communication backend. Or perhaps it’s an iOS app providing over-the-air access to documents. Whatever your reason, CocoaHTTPServer can get the job done. It provides:

Built in support for bonjour broadcasting
IPv4 and IPv6 support
Asynchronous networking using GCD and standard sockets
Password protection support
SSL/TLS encryption support
Extremely FAST and memory efficient
Extremely scalable (built entirely upon GCD)
Heavily commented code
Very easily extensible
WebDAV is supported too!

CocoaHTTPServer是为Mac OS X或者iOS应用封装的一个小的,轻量的,可嵌入的HTTP服务器。
开发者有时在他们的应用需要一个嵌入的HTTP服务器。有可能是一个远程监控的服务器应用,或者可能是一个使用HTTP后台通迅的桌面应用,或者是一个iOS应用程序提供的文件的存取。不管你基于什么原因,CocoaHTTPServer能完成这项工作。它提供了:
内置bonjour广播
支持IPv4和IPv6
适用GCD和标准sockets异步完成网络工作
支持密码保护
支持SSL/TLS编码
非常快捷,高效内存
可拓展性高(完全GCD编译)
丰富的代码描述
延展很简单
也支持WebDAV

简单适用
1. 导入下载好的代码;
2. 创建HTTP服务器;

httpServer = [[HTTPServer alloc] init];  
[httpServer setType:@"_http._tcp."];  
// [httpServer setPort:87878];  
NSString * webLocalPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Web"];  
[httpServer setDocumentRoot:webLocalPath];  

NSError * error;  
if([httpServer start:&error])  
{  
   NSLog(@"start server success in port %d %@",[httpServer listeningPort],[httpServer publishedName]);  
}  
else  
{  
   NSLog(@"启动失败");  
}  

注意:[httpServer setPort:87878]; 如果不设置,会随机分配port。建议在测试时使用该方法,生产上随机分配,以免和其他端口冲突。
3. 指定web根目录;做过web开发的同学应该都清楚,需要配置web加载的路径。这里,我们将在应用的documents建一个web目录作为根目录。
注意:在拖拽web的文件夹的时候一定用真实的目录,而不是xcode的虚拟目录。

现在运行应用,如果是在局域网,根据手机的IP和运行时产生的端口号,将连接在浏览器中打开,你会发现这是一个空网页。

现在手机服务器应用已经好了,接下来我们将处理web页面。

 类似资料: