首页 文章 精选 留言 我的

精选列表

搜索[代码生成],共10000篇文章
优秀的个人博客,低调大师

代码处理iOS的横竖屏旋转

一、监听屏幕旋转方向 在处理iOS横竖屏时,经常会和UIDeviceOrientation、UIInterfaceOrientation和UIInterfaceOrientationMask这三个枚举类型打交道,它们从不同角度描述了屏幕旋转方向。 1、UIDeviceOrientation:设备方向 iOS的设备方向是通过iOS的加速计来获取的。 1)iOS定义了以下七种设备方向 typedefNS_ENUM(NSInteger,UIDeviceOrientation){ UIDeviceOrientationUnknown,//未知方向,可能是设备(屏幕)斜置 UIDeviceOrientationPortrait,//设备(屏幕)直立 UIDeviceOrientationPortraitUpsideDown,//设备(屏幕)直立,上下顛倒 UIDeviceOrientationLandscapeLeft,//设备(屏幕)向左横置 UIDeviceOrientationLandscapeRight,//设备(屏幕)向右橫置 UIDeviceOrientationFaceUp,//设备(屏幕)朝上平躺 UIDeviceOrientationFaceDown//设备(屏幕)朝下平躺 }; 说明:UIDeviceOrientation参考home键方向,如:home方向在右,设备(屏幕)方向向左(UIDeviceOrientationLandscapeLeft) 2)读取设备方向 UIDevice单例代表当前的设备。从这个单例中可以获得的信息设备,如设备方向orientation。 UIDeviceOrientationdeviceOrientation=[UIDevicecurrentDevice].orientation; 3)监听、处理和移除 设备方向改变的通知 当设备方向变化时候,发出UIDeviceOrientationDidChangeNotification通知;注册监听该通知,可以针对不同的设备方向处理视图展示。 //开启和监听设备旋转的通知(不开启的话,设备方向一直是UIInterfaceOrientationUnknown) if(![UIDevicecurrentDevice].generatesDeviceOrientationNotifications){ [[UIDevicecurrentDevice]beginGeneratingDeviceOrientationNotifications]; } [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleDeviceOrientationChange:) name:UIDeviceOrientationDidChangeNotificationobject:nil]; //设备方向改变的处理 -(void)handleDeviceOrientationChange:(NSNotification*)notification{ UIDeviceOrientationdeviceOrientation=[UIDevicecurrentDevice].orientation; switch(ddeviceOrientation){ caseUIDeviceOrientationFaceUp: NSLog(@"屏幕朝上平躺"); break; caseUIDeviceOrientationFaceDown: NSLog(@"屏幕朝下平躺"); break; caseUIDeviceOrientationUnknown: NSLog(@"未知方向"); break; caseUIDeviceOrientationLandscapeLeft: NSLog(@"屏幕向左横置"); break; caseUIDeviceOrientationLandscapeRight: NSLog(@"屏幕向右橫置"); break; caseUIDeviceOrientationPortrait: NSLog(@"屏幕直立"); break; caseUIDeviceOrientationPortraitUpsideDown: NSLog(@"屏幕直立,上下顛倒"); break; default: NSLog(@"无法辨识"); break; } } //最后在dealloc中移除通知和结束设备旋转的通知 -(void)dealloc{ //... [[NSNotificationCenterdefaultCenter]removeObserver:self]; [[UIDevicecurrentDevice]endGeneratingDeviceOrientationNotifications]; 说明:手机锁定竖屏后,UIDeviceOrientationDidChangeNotification通知就失效了。 2、UIInterfaceOrientation:界面方向 界面方向是反应iOS中界面的方向,它和Home按钮的方向是一致的。 1)iOS定义了以下五种界面方向 typedefNS_ENUM(NSInteger,UIInterfaceOrientation){ UIInterfaceOrientationUnknown=UIDeviceOrientationUnknown,//未知方向 UIInterfaceOrientationPortrait=UIDeviceOrientationPortrait,//界面直立 UIInterfaceOrientationPortraitUpsideDown=UIDeviceOrientationPortraitUpsideDown,//界面直立,上下颠倒 UIInterfaceOrientationLandscapeLeft=UIDeviceOrientationLandscapeRight,//界面朝左 UIInterfaceOrientationLandscapeRight=UIDeviceOrientationLandscapeLeft//界面朝右 }__TVOS_PROHIBITED; 说明:从定义可知,界面方向和设别方向有对应关系,如界面的竖直方向就是 设备的竖直方向:UIInterfaceOrientationUnknown = UIDeviceOrientationUnknown 2)读取界面方向 UIInterfaceOrientation和状态栏有关,通过UIApplication的单例调用statusBarOrientation来获取 UIInterfaceOrientationinterfaceOrientation=[[UIApplicationsharedApplication]statusBarOrientation]; 3)监听、处理和移除 界面方向改变的通知 当界面方向变化时候,先后发出UIApplicationWillChangeStatusBarOrientationNotification和UIApplicationDidChangeStatusBarOrientationNotification通知;注册监听这两个通知,可以针对不同的界面方向处理视图展示。 //以监听UIApplicationDidChangeStatusBarOrientationNotification通知为例 [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleStatusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotificationobject:nil]; //界面方向改变的处理 -(void)handleStatusBarOrientationChange:(NSNotification*)notification{ UIInterfaceOrientationinterfaceOrientation=[[UIApplicationsharedApplication]statusBarOrientation]; switch(interfaceOrientation){ caseUIInterfaceOrientationUnknown: NSLog(@"未知方向"); break; caseUIInterfaceOrientationPortrait: NSLog(@"界面直立"); break; caseUIInterfaceOrientationPortraitUpsideDown: NSLog(@"界面直立,上下颠倒"); break; caseUIInterfaceOrientationLandscapeLeft: NSLog(@"界面朝左"); break; caseUIInterfaceOrientationLandscapeRight: NSLog(@"界面朝右"); break; default: break; } } //最后在dealloc中移除通知 -(void)dealloc{ //... [[NSNotificationCenterdefaultCenter]removeObserver:self]; [[UIDevicecurrentDevice]endGeneratingDeviceOrientationNotifications]; } 说明:手机锁定竖屏后,UIApplicationWillChangeStatusBarOrientationNotification和UIApplicationDidChangeStatusBarOrientationNotification通知也失效了。 3、UIInterfaceOrientationMask UIInterfaceOrientationMask是为了集成多种UIInterfaceOrientation而定义的类型,和ViewController相关,一共有7种 1)iOS中的UIInterfaceOrientationMask定义 typedefNS_OPTIONS(NSUInteger,UIInterfaceOrientationMask){ UIInterfaceOrientationMaskPortrait=(1<<UIInterfaceOrientationPortrait), UIInterfaceOrientationMaskLandscapeLeft=(1<<UIInterfaceOrientationLandscapeLeft), UIInterfaceOrientationMaskLandscapeRight=(1<<UIInterfaceOrientationLandscapeRight), UIInterfaceOrientationMaskPortraitUpsideDown=(1<<UIInterfaceOrientationPortraitUpsideDown), UIInterfaceOrientationMaskLandscape=(UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight), UIInterfaceOrientationMaskAll=(UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight|UIInterfaceOrientationMaskPortraitUpsideDown), UIInterfaceOrientationMaskAllButUpsideDown=(UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight), }__TVOS_PROHIBITED; 2)UIInterfaceOrientationMask的使用 在ViewController可以重写- (UIInterfaceOrientationMask)supportedInterfaceOrientations方法返回类型,来决定UIViewController可以支持哪些界面方向。 //支持界面直立 -(UIInterfaceOrientationMask)supportedInterfaceOrientations{ returnUIInterfaceOrientationMaskPortrait; } 总结:UIDeviceOrientation(设备方向)和UIInterfaceOrientation(屏幕方向)是两个不同的概念。前者代表了设备的一种状态,而后者是屏幕为了应对不同的设备状态,做出的用户界面上的响应。在iOS设备旋转时,由UIKit接收到旋转事件,然后通过AppDelegate通知当前程序的UIWindow对象,UIWindow对象通知它的rootViewController,如果该rootViewController支持旋转后的屏幕方向,完成旋转,否则不旋转;弹出的ViewController也是如此处理。 二、视图控制器中旋转方向的设置 0、关于禁止横屏的操作(不建议) 比较常规的方法有两种。 方法1:在项目的General–>Deployment Info–>Device Orientation中,只勾选Portrait(竖屏) 勾选Portrait.png 方法2:Device Orientation默认设置,在Appdelegate中实现supportedInterfaceOrientationsForWindow:只返回UIInterfaceOrientationMaskPortraitt(竖屏) -(NSUInteger)application:(UIApplication*)applicationsupportedInterfaceOrientationsForWindow:(UIWindow*)window{ returnUIInterfaceOrientationMaskPortrait; } 说明:极少的APP中所有界面都是竖屏的,因为总会有界面需要支持横屏,如视频播放页。所以不建议设置禁止APP页面横屏。 下面介绍如何让项目中的 视图控制器中旋转方向的设置 1、APP支持多个方向 APP支持多个方向.png 说明:如此,APP支持横屏和竖屏了,但是具体视图控制器支持的页面方向还需要进一步处理。由于不支持竖屏颠倒(Upside Down),即使设备上下颠倒,通过API也不会获得设备、屏幕上下颠倒方向的。 2、支持ViewController屏幕方向设置 1)关键函数 视图控制器支持的界面方向主要由以下三个函数控制 //是否自动旋转,返回YES可以自动旋转,返回NO禁止旋转 -(BOOL)shouldAutorotateNS_AVAILABLE_IOS(6_0)__TVOS_PROHIBITED; //返回支持的方向 -(UIInterfaceOrientationMask)supportedInterfaceOrientationsNS_AVAILABLE_IOS(6_0)__TVOS_PROHIBITED; //由模态推出的视图控制器优先支持的屏幕方向 -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentationNS_AVAILABLE_IOS(6_0)__TVOS_PROHIBITED; 2) QSBaseViewController设置 //QSBaseViewController.h @interfaceQSBaseController:UIViewController @end //QSBaseViewController.m @implementationQSBaseController //#pragmamark-控制屏幕旋转方法 //是否自动旋转,返回YES可以自动旋转,返回NO禁止旋转 -(BOOL)shouldAutorotate{ returnNO; } //返回支持的方向 -(UIInterfaceOrientationMask)supportedInterfaceOrientations{ returnUIInterfaceOrientationMaskPortrait; } //由模态推出的视图控制器优先支持的屏幕方向 -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ returnUIInterfaceOrientationPortrait; } @end 说明1:QSBaseViewController默认不支持旋转,只支持 界面竖直方向,项目中的Controller都继承自QSBaseViewController,可以通过重写这三个方法来让Controller支持除竖屏之外的方向或旋转。 3) 在QSNavigationController设置 目标:通过QSNavigationController来push视图控制器时,把支持屏幕旋转的设置交给最新push进来([self.viewControllers lastObject])的viewController来设置。 //QSNavigationController.h @interfaceQSNavigationController:UINavigationController @end //QSNavigationController.m @implementationQSNavigationController #pragmamark-控制屏幕旋转方法 -(BOOL)shouldAutorotate{ return[[self.viewControllerslastObject]shouldAutorotate]; } -(UIInterfaceOrientationMask)supportedInterfaceOrientations{ return[[self.viewControllerslastObject]supportedInterfaceOrientations]; } -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return[[self.viewControllerslastObject]preferredInterfaceOrientationForPresentation]; } @end 4) 在QSTabBarController设置 目标:TabBarController通常作为整个程序的rootViewController,UITabBar上面显示的每一个Tab都对应着一个ViewController;每点击一个Tab,出现的ViewController(self.selectedViewController)对屏幕旋转和支持方向的设置 交给其自身去控制。 //QSTabBarController.h @interfaceQSTabBarController:UITabBarController @end //QSTabBarController.m @implementationQSTabBarController #pragmamark-控制屏幕旋转方法 -(BOOL)shouldAutorotate{ return[self.selectedViewControllershouldAutorotate]; } -(UIInterfaceOrientationMask)supportedInterfaceOrientations{ return[self.selectedViewControllersupportedInterfaceOrientations]; } -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return[self.selectedViewControllerpreferredInterfaceOrientationForPresentation]; } @end 三、屏幕旋转方向下的视图处理 1、屏幕旋转时,建议监听UIApplicationDidChangeStatusBarOrientationNotification 原因1:supportedInterfaceOrientations方法中最终返回的是 多个界面方向。 原因2(最重要的原因):我们真正要处理的是页面方向发生旋转UI的变化。而在设备的物理方向发生旋转的时候,如果此时当前控制器的页面并没有旋转,我们这时改变UI布局,可能就发生问题了。 2、屏幕的宽高处理 1)在iOS 8之后,当屏幕旋转的时候,[[UIScreen mainScreen] bounds]也发生了改变。如横屏时候的屏幕宽度 其实是竖屏的时候屏幕的高度。 2)我们处理视图布局时候,如果使用到屏幕的宽高,不要直接使用SCREEN_HEIGHT和SCREEN_WIDTH,而使用SCREEN_MIN和SCREEN_MAX #defineSCREEN_HEIGHTCGRectGetHeight([[UIScreenmainScreen]bounds]) #defineSCREEN_WIDTHCGRectGetWidth([[UIScreenmainScreen]bounds]) #defineSCREEN_MINMIN(SCREEN_HEIGHT,SCREEN_WIDTH) #defineSCREEN_MAXMAX(SCREEN_HEIGHT,SCREEN_WIDTH) 说明:竖屏时候,宽是SCREEN_MIN,高是SCREEN_MAX;横屏时候,宽是SCREEN_MAX,高是SCREEN_MIN。 3、屏幕旋转下处理Demo //监听UIApplicationDidChangeStatusBarOrientationNotification的处理 -(void)handleStatusBarOrientationChange:(NSNotification*)notification{ UIInterfaceOrientationinterfaceOrientation=[[UIApplicationsharedApplication]statusBarOrientation]; BOOLisLandscape=NO; switch(interfaceOrientation){ caseUIInterfaceOrientationUnknown: NSLog(@"未知方向"); break; caseUIInterfaceOrientationPortrait: caseUIInterfaceOrientationPortraitUpsideDown: isLandscape=NO; break; caseUIInterfaceOrientationLandscapeLeft: caseUIInterfaceOrientationLandscapeRight: isLandscape=YES; break; default: break; } if(isLandscape){ self.tableView.frame=CGRectMake(0,0,SCREEN_MAX,SCREEN_MIN-44); }else{ self.tableView.frame=CGRectMake(0,0,SCREEN_MIN,SCREEN_MAX-64); } [self.tableViewreloadData]; } 说明:当然也可以选择使用Masonry这样优秀的AutoLayout布局第三方库来处理,storyBoard来布局次之。 4、屏幕旋转下处理Demo效果图 竖屏下效果.png 横屏下效果.png 5、屏幕旋转处理的建议 1)旋转前后,view当前显示的位置尽量不变 2)旋转过程中,暂时界面操作的响应 3)视图中有tableview的话,旋转后,强制 [tableview reloadData],保证在方向变化以后,新的row能够充满全屏。 四、强制横屏 APP中某些页面,如视频播放页,一出现就要求横屏。这些横屏页面或模态弹出、或push进来。 1、模态弹出ViewController情况下 强制横屏的设置 //QSShow3Controller.m -(BOOL)shouldAutorotate{ returnNO; } -(UIInterfaceOrientationMask)supportedInterfaceOrientations{ returnUIInterfaceOrientationMaskLandscapeRight; } -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ returnUIInterfaceOrientationLandscapeRight; } //模态弹出 QSShow3Controller*vc=[[QSShow3Controlleralloc]init]; [selfpresentViewController:vcanimated:YEScompletion:nil]; 说明:这种情况比较简单处理。 2、push推入ViewController情况下 强制横屏的设置 //QSShow4Controller.m -(void)viewWillAppear:(BOOL)animated{ [superviewWillAppear:animated]; [selfsetInterfaceOrientation:UIInterfaceOrientationLandscapeRight]; } //强制转屏(这个方法最好放在BaseVController中) -(void)setInterfaceOrientation:(UIInterfaceOrientation)orientation{ if([[UIDevicecurrentDevice]respondsToSelector:@selector(setOrientation:)]){ SELselector=NSSelectorFromString(@"setOrientation:"); NSInvocation*invocation=[NSInvocationinvocationWithMethodSignature:[UIDeviceinstanceMethodSignatureForSelector:selector]]; [invocationsetSelector:selector]; [invocationsetTarget:[UIDevicecurrentDevice]]; //从2开始是因为前两个参数已经被selector和target占用 [invocationsetArgument:&orientationatIndex:2]; [invocationinvoke]; } } //必须返回YES -(BOOL)shouldAutorotate{ returnYES; } -(UIInterfaceOrientationMask)supportedInterfaceOrientations{ returnUIInterfaceOrientationMaskLandscapeRight; } //Push推入 QSShow4Controller*vc=[[QSShow4Controlleralloc]init]; [self.navigationControllerpushViewController:vcanimated:YES]; 说明:苹果不允许直接调用setOrientation方法,否则有被拒的风险;使用NSInvocation对象给[UIDevice currentDevice]发消息,强制改变设备方向,使其页面方向对应改变,这是苹果允许的。 五、其他 1、 APP启动时,手机横屏下,首页UI(该页面只支持竖屏)出错(add by 2017/6/20) //设置设置状态栏竖屏 [[UIApplicationsharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait]; 本文作者:佚名 来源:51CTO

优秀的个人博客,低调大师

《PHP精粹:编写高效PHP代码》——导读

目 录 第1章 面向对象编程1.1 为什么要使用面向对象编程1.2 OOP简介1.3 对象的继承1.4 对象和函数1.5 public、private以及protected1.6 接口1.7 异常1.8 更多神奇的方法1.9 本章小结第2章 数据库2.1 数据持久化和Web应用程序2.2 选择如何存储数据2.3 用MySQL建立一个食谱网站2.4 PHP数据库对象2.5 处理PDO中的错误2.6 高级PDO特征2.7 设计数据库2.8 数据库—排序第3章 API3.1 开始之前3.2 面向服务的架构3.3 数据格式3.4 HTTP:超文本传输协议3.5 设计一个Web服务3.6 提供的服务

优秀的个人博客,低调大师

代码显示Android未来可能“Windows化”

下一版Android系统代号为“Android N”,其最重要的新功能在于原生地支持分屏模式。这看起来将类似于Windows 10。那么,如果Android系统的行为也变得类似于Windows,将会发生什么? 谷歌似乎正在考虑这样的方案。Android N的官方文档提到了“自由变形”模式。这一模式支持用户自主调整应用窗口大小。 在启用分屏模式时,“大尺寸设备”的制造商需要激活这一功能,因此如果用户使用的是4.5英寸的摩托罗拉Moto G,那么将不会看到这项功能。 需要指出的是,Android已在一定程度上支持浮动应用,FacebookMessenger的“Chat Heats”就是最知名的一个例子。不过,目前这样的应用还很少,同时也不支持用户自行调整应用窗口尺寸。 苹果iPad Pro和微软Surface正试图重新定义未来的办公环境,目前看来谷歌也将采取类似举措。尽管我们尚未看到谷歌在这一领域的具体行动,但相对于此前的移动操作系统,Android N将会更好地支持窗口化应用。 在短时间内,Android N还不会成为OS X和Windows 10的竞争对手,但用户对窗口化应用的需求正在出现。凭借庞大的移动应用选择,Android N可以提供一个对触控操作友好的桌面操作系统,而这是Windows 8想实现却未能实现的。 谷歌此前多次否认,有计划将Android改造成桌面操作系统,或是将其整合至当前的笔记本平台Chrome OS。不过从Android N来看,谷歌并未放弃这样的设想。 本文转自d1net(转载)

优秀的个人博客,低调大师

Python 学习笔记 - socketserver源代码剖析

前面学习的例子都是单线程的socket收发;如果有多个用户同时接入,那么除了第一个连入的,后面的都会处于挂起等待的状态,直到当前连接的客户端断开为止。 通过使用socketserver,我们可以实现并发的连接。 socketserver的使用很简单: 首先看个简单的例子 服务端: 自己定义一个类,继承socketserver.baserequesthandler; 然后定义一个方法 handle() 然后通过socketserver.threadingTCPServer指定套接字和自己定义的类,每次当客户端连入的时候,会自动实例化一个对象,然后通过server_forever()不断循环读写数据。 #!/usr/bin/envpython #-*-coding:utf-8-*- #AuthorYuanLi importsocketserver classmysocketserver(socketserver.BaseRequestHandler): defhandle(self): conn=self.request conn.sendall(bytes("WelcometotheTestsystem.",encoding='utf-8')) whileTrue: try: data=conn.recv(1024) iflen(data)==0:break print("[%s]sends%s"%(self.client_address,data.decode())) conn.sendall(data.upper()) exceptException: break if__name__=='__main__': server=socketserver.ThreadingTCPServer(('127.0.0.1',8009),mysocketserver) server.serve_forever() 客户端: #!/usr/bin/envpython #-*-coding:utf-8-*- #AuthorYuanLi importsocket ip_port=('127.0.0.1',8009) s=socket.socket() s.connect(ip_port) data=s.recv(1024) print(data.decode()) whileTrue: send_data=input("Data>>>") s.send(bytes(send_data,encoding='utf-8')) recv_data=s.recv(1024) print(recv_data.decode()) 上面的效果是多个客户端可以同时连入服务器,输入字母,返回大写字母。 客户端没啥好说的,这个和单线程的操作一样;但是服务器咋一看很混乱。我们可以通过剖析源码来弄清他的执行过程。 这个类的基本结构是如下所示的,我们按照顺序来跑一次看看他怎么调用的 1. 首先执行的这句话,很明显ThredingTCPServer是一个类,点进去看看他的实例化过程 server=socketserver.ThreadingTCPServer(('127.0.0.1',8009),mysocketserver) 2. 点着Ctrl键,点击这个类,PyCharm会自动打开对应的源码,可以看见这个类又继承了两个父类ThredingMixIn和TCPServer classThreadingTCPServer(ThreadingMixIn,TCPServer):pass 因为他的内容是pass,啥也没做,根据继承的顺序,我们继续往上(从左到右)找init构造函数; 3. ThreadingMixIn里面没有构造函数,那就继续往右找,TCPServer里面倒是有构造函数,但是他又调用了他父类BaseServer的构造函数,顺着看上去,发现他就是封装了几个值在里面,注意 self.RequestHandlerClass = RequestHandlerClass把我们自己定义的类传进去了 def__init__(self,server_address,RequestHandlerClass): """Constructor.Maybeextended,donotoverride.""" self.server_address=server_address self.RequestHandlerClass=RequestHandlerClass self.__is_shut_down=threading.Event() self.__shutdown_request=False 4.接下来,在TCPServer的构造函数里面,他执行了bind,listen的操作,这个和单线程的操作是一样的。到此为止,一个初始化的过程基本就完成了。 5.接下来,执行了server.serve_forever()的操作,我们看看内部是怎么调用的。在这个函数里面,使用了selector的IO多路复用的技术,循环的读取一个文件的操作。接着调用了_handle_request_noblock()函数 try: #XXX:Considerusinganotherfiledescriptororconnectingtothe #sockettowakethisupinsteadofpolling.Pollingreducesour #responsivenesstoashutdownrequestandwastescpuatallother #times. with_ServerSelector()asselector: selector.register(self,selectors.EVENT_READ) whilenotself.__shutdown_request: ready=selector.select(poll_interval) ifready: self._handle_request_noblock() self.service_actions() 6.每次调用函数的时候都记住查找的顺序,从下往上,从左往右,最后在最上面的BaseServer再次找到这个函数,这个函数里面又调用了 process_request函数 """ try: request,client_address=self.get_request() exceptOSError: return ifself.verify_request(request,client_address): try: self.process_request(request,client_address) 一定要记住继承的顺序!!顺序!!顺序!! 因为baseserver自己有process_request的方法,ThreadingTCPServer也有同名的方法,当他调用的时候,按照顺序,是执行的ThreadingTCPServer里面的方法!! 可以看见他开了一个多线程 defprocess_request(self,request,client_address): """Startanewthreadtoprocesstherequest.""" t=threading.Thread(target=self.process_request_thread, args=(request,client_address)) t.daemon=self.daemon_threads t.start() 在他调用的process_request_thread里面,他又调用了finsih_request defprocess_request_thread(self,request,client_address): """SameasinBaseServerbutasathread. Inaddition,exceptionhandlingisdonehere. """ try: self.finish_request(request,client_address) self.shutdown_request(request) except: self.handle_error(request,client_address) self.shutdown_request(request) finish_request里面有对我们自定义的类做了一个实例化的操作 deffinish_request(self,request,client_address): """FinishonerequestbyinstantiatingRequestHandlerClass.""" self.RequestHandlerClass(request,client_address,self) 因为我们自定义的类没有构造函数,他会去父类寻找,父类里面会尝试执行handle()方法,这就是为什么我们需要在自定义的类里面定义一个同名的方法,然后把所有需要执行的内容都放在这里。 def__init__(self,request,client_address,server): self.request=request self.client_address=client_address self.server=server self.setup() try: self.handle() 到此,socketserver一个完整的过程就结束了

优秀的个人博客,低调大师

ECSHOP代码详解之INIT.PHP

<?php /** * ECSHOP 前台公用文件 */ //防止非法调用 defined-判断常量是否已定义,如果没返回false if (!defined('IN_ECS')) { die('Hacking attempt');//die-直接终止程序并输出 } //报告所有错误 error_reporting(E_ALL); //如果获取不到本文件 if (__FILE__ == '') { die('Fatal error code: 0'); } /*预定义常量 __LINE__ 文件中的当前行号。 __FILE__ 文件的完整路径和文件名。 __FUNCTION__ 函数名称(这是 PHP 4.3.0 新加的)。 __CLASS__ 类的名称(这是 PHP 4.3.0 新加的)。 __METHOD__ 类的方法名(这是 PHP 5.0.0 新加的)。 */ /* 取得当前商城所在的根目录 */ define('ROOT_PATH', str_replace('includes/init.php', '', str_replace('\\', '/', __FILE__))); //检测是否已安装 if (!file_exists(ROOT_PATH . 'data/install.lock') && !file_exists(ROOT_PATH . 'includes/install.lock') && !defined('NO_CHECK_INSTALL')) { header("Location: ./install/index.php\n"); exit; } /* 初始化设置 */ @ini_set('memory_limit', '64M');//ini_set设置php.ini中的设置,memory_limit设定一个脚本所能够申请到的最大内存字节数 @ini_set('session.cache_expire', 180);//指定会话页面在客户端cache中的有效期限(分钟),单位为分钟。 @ini_set('session.use_trans_sid', 0);//关闭自动把session id嵌入到web的URL中 @ini_set('session.use_cookies', 1);//允许使用cookie在客户端保存会话ID @ini_set('session.auto_start', 0);//在客户访问任何页面时都自动初始化会话,0-禁止 @ini_set('display_errors', 1);//是否显示错误 if (DIRECTORY_SEPARATOR == '\\')//如果装在windows上(DIRECTORY_SEPARATOR路径分隔符,linux上就是’/’ windows上是’\’) { @ini_set('include_path', '.;' . ROOT_PATH);//include目录为当前目录和网站根目录,windows下用';'分隔 } else { @ini_set('include_path', '.:' . ROOT_PATH);//include目录为当前目录和网站根目录,linux下用':'分隔 } require(ROOT_PATH . 'data/config.php');//包含配置文件(数据库相关) if (defined('DEBUG_MODE') == false)//如果常量DEBUG_MODE没有定义则定义为0,DEBUG_MODE用于设置ecshp的使用模式 { define('DEBUG_MODE', 0); } //设定用于所有日期时间函数的默认时区 if (PHP_VERSION >= '5.1' && !empty($timezone)) { date_default_timezone_set($timezone);//date_default_timezone_set 设置时区 } //$_SERVER['PHP_SELF']返回当前页面,获取$_SERVER['PHP_SELF']最好用htmlspecialchars过滤一下,存在XSS漏洞 $php_self = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; if ('/' == substr($php_self, -1))//如果是"/"结尾,则加上index.php { $php_self .= 'index.php'; } define('PHP_SELF', $php_self);//放入常量 require(ROOT_PATH . 'includes/inc_constant.php');//包含预定义常量文件 require(ROOT_PATH . 'includes/cls_ecshop.php');//基础类 文件 require(ROOT_PATH . 'includes/cls_error.php');//错误类 文件 require(ROOT_PATH . 'includes/lib_time.php');//时间函数 require(ROOT_PATH . 'includes/lib_base.php');//基础函数库 require(ROOT_PATH . 'includes/lib_common.php');//基础函数库 require(ROOT_PATH . 'includes/lib_main.php');//公用函数库 require(ROOT_PATH . 'includes/lib_insert.php');//动态内容函数库 require(ROOT_PATH . 'includes/lib_goods.php');//商品相关函数库 require(ROOT_PATH . 'includes/lib_article.php');//文章及文章分类相关函数库 /* 对用户传入的变量进行转义操作。*/ if (!get_magic_quotes_gpc()) { if (!empty($_GET)) { $_GET = addslashes_deep($_GET); } if (!empty($_POST)) { $_POST = addslashes_deep($_POST); } $_COOKIE = addslashes_deep($_COOKIE); $_REQUEST = addslashes_deep($_REQUEST); } /* 创建 ECSHOP 对象 */ $ecs = new ECS($db_name, $prefix);//参数说明:数据库名 表前缀 define('DATA_DIR', $ecs->data_dir());//数据目录 define('IMAGE_DIR', $ecs->image_dir());//图片目录 /* 初始化数据库类 */ require(ROOT_PATH . 'includes/cls_mysql.php'); $db = new cls_mysql($db_host, $db_user, $db_pass, $db_name); /* 设置不允许进行缓存的表 */ $db->set_disable_cache_tables(array($ecs->table('sessions'), $ecs->table('sessions_data'), $ecs->table('cart'))); $db_host = $db_user = $db_pass = $db_name = NULL; /* 创建错误处理对象 */ $err = new ecs_error('message.dwt'); /* 载入系统参数 */ $_CFG = load_config(); //载入配置信息函数在lib_common.php /* 载入语言文件 */ require(ROOT_PATH . 'languages/' . $_CFG['lang'] . '/common.php'); if ($_CFG['shop_closed'] == 1) { /* 商店关闭了,输出关闭的消息 */ header('Content-type: text/html; charset='.EC_CHARSET); die('<div style="margin: 150px; text-align: center; font-size: 14px"><p>' . $_LANG['shop_closed'] . '</p><p>' . $_CFG['close_comment'] . '</p></div>'); } //判断是否为搜索引擎蜘蛛 函数在lib_main.php if (is_spider()) { /* 如果是蜘蛛的访问,那么默认为访客方式,并且不记录到日志中 */ if (!defined('INIT_NO_USERS')) { define('INIT_NO_USERS', true); /* 整合UC后,如果是蜘蛛访问,初始化UC需要的常量 */ if($_CFG['integrate_code'] == 'ucenter') { $user = & init_users(); } } $_SESSION = array(); $_SESSION['user_id'] = 0; $_SESSION['user_name'] = ''; $_SESSION['email'] = ''; $_SESSION['user_rank'] = 0; $_SESSION['discount'] = 1.00; } //非搜索引擎蜘蛛,记录session if (!defined('INIT_NO_USERS')) { /* 初始化session */ include(ROOT_PATH . 'includes/cls_session.php'); $sess = new cls_session($db, $ecs->table('sessions'), $ecs->table('sessions_data')); define('SESS_ID', $sess->get_session_id()); } //如果使用Smarty if (!defined('INIT_NO_SMARTY')) { header('Cache-control: private'); header('Content-type: text/html; charset='.EC_CHARSET); /* 创建 Smarty 对象。*/ require(ROOT_PATH . 'includes/cls_template.php'); $smarty = new cls_template; $smarty->cache_lifetime = $_CFG['cache_time'];//缓存时间 $smarty->template_dir = ROOT_PATH . 'themes/' . $_CFG['template'];//模板所在 $smarty->cache_dir = ROOT_PATH . 'temp/caches';//缓存所在 $smarty->compile_dir = ROOT_PATH . 'temp/compiled';//模板编译后的文件所在 if ((DEBUG_MODE & 2) == 2)//如果常量DEBUG_MODE值为 2、3、6、7.时 { $smarty->direct_output = true; //不使用缓存直接输出 $smarty->force_compile = true; //强行编译 } else { $smarty->direct_output = false; $smarty->force_compile = false; } $smarty->assign('lang', $_LANG); $smarty->assign('ecs_charset', EC_CHARSET); if (!empty($_CFG['stylename']))//如果自己定义样式文件就用自己的 { $smarty->assign('ecs_css_path', 'themes/' . $_CFG['template'] . '/style_' . $_CFG['stylename'] . '.css'); } else { $smarty->assign('ecs_css_path', 'themes/' . $_CFG['template'] . '/style.css'); } } //非搜索引擎爬虫,记录用户信息 if (!defined('INIT_NO_USERS')) { /* 会员信息 初始化会员数据 lib_common.php */ $user =& init_users(); if (!isset($_SESSION['user_id'])) { /* 获取投放站点的名称 */ $site_name = isset($_GET['from']) ? $_GET['from'] : addslashes($_LANG['self_site']); $from_ad = !empty($_GET['ad_id']) ? intval($_GET['ad_id']) : 0; $_SESSION['from_ad'] = $from_ad; // 用户点击的广告ID $_SESSION['referer'] = stripslashes($site_name); // 用户来源 unset($site_name); if (!defined('INGORE_VISIT_STATS')) { visit_stats(); } } if (empty($_SESSION['user_id'])) { if ($user->get_cookie()) { /* 如果会员已经登录并且还没有获得会员的帐户余额、积分以及优惠券 */ if ($_SESSION['user_id'] > 0) { update_user_info(); } } else { $_SESSION['user_id'] = 0; $_SESSION['user_name'] = ''; $_SESSION['email'] = ''; $_SESSION['user_rank'] = 0; $_SESSION['discount'] = 1.00; if (!isset($_SESSION['login_fail'])) { $_SESSION['login_fail'] = 0; } } } /* 设置推荐会员 */ if (isset($_GET['u'])) { set_affiliate(); } if (isset($smarty)) { $smarty->assign('ecs_session', $_SESSION); } } if ((DEBUG_MODE & 1) == 1)//如果常量DEBUG_MODE值为 1、3、5、7.时 { error_reporting(E_ALL);//报告全部错误 } else { error_reporting(E_ALL ^ E_NOTICE); //报告除E_NOTICE以外的所有错误 } if ((DEBUG_MODE & 4) == 4)//如果常量DEBUG_MODE值为 4、5、6、7.时,调试程序 { include(ROOT_PATH . 'includes/lib.debug.php');// } /* 判断是否支持 Gzip 模式 如果使用SMARTY同时设置了网页压缩,则启用压缩 */ if (!defined('INIT_NO_SMARTY') && gzip_enabled()) { ob_start('ob_gzhandler');//压缩后放入缓冲区 } else { ob_start();//打开缓冲区,把下面要显示的内容先缓在服务器 } /* ob_start相关函数了解: 1、Flush:刷新缓冲区的内容,输出。 函数格式:flush() 说明:这个函数经常使用,效率很高。 2、ob_start :打开输出缓冲区 函数格式:void ob_start(void) 说明:当缓冲区激活时,所有来自PHP程序的非文件头信息均不会发送,而是保存在内部缓冲区。为了输出缓冲区的内容,可以使用ob_end_flush()或flush()输出缓冲区的内容。 、ob_get_contents :返回内部缓冲区的内容。 使用方法:string ob_get_contents(void) 说明:这个函数会返回当前缓冲区中的内容,如果输出缓冲区没有激活,则返回 FALSE 。 4、ob_get_length:返回内部缓冲区的长度。 使用方法:int ob_get_length(void) 说明:这个函数会返回当前缓冲区中的长度;和ob_get_contents一样,如果输出缓冲区没有激活。则返回 FALSE。 5、ob_end_flush :发送内部缓冲区的内容到浏览器,并且关闭输出缓冲区。 使用方法:void ob_end_flush(void) 说明:这个函数发送输出缓冲区的内容(如果有的话)。 6、ob_end_clean:删除内部缓冲区的内容,并且关闭内部缓冲区 使用方法:void ob_end_clean(void) 说明:这个函数不会输出内部缓冲区的内容而是把它删除! 7、ob_implicit_flush:打开或关闭绝对刷新 使用方法:void ob_implicit_flush ([int flag]) 说明:使用过Perl的人都知道$|=x的意义,这个字符串可以打开/关闭缓冲区,而ob_implicit_flush函数也和那个一样,默认为关闭缓冲区,打开绝对输出后,每个脚本输出都直接发送到浏览器,不再需要调用 flush() */ ?>

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册