如下所示是.h文件。
"object-c
typedef NS_ENUM(NSUInteger,BSDServerErrorCode) {
NOERROR,
SOCKETERROR,
BINDERROR,
LISTENERROR,
CFSOCKETCREATEERROR,
ACCEPTINGERROR
};
@interface BIDCFSocketServer : NSObject
@property (nonatomic)CFSocketRef sRef;
@property (nonatomic) int listenfd, errorCode;
-(instancetype)initOnPort:(int)port;
@end
如下图代码所示的是.m文件;
"object-c
#define LISTENQ 1024
@implementation BIDCFSocketServer
-(instancetype)initOnPort:(int)port{
struct sockaddr_in servaddr;
CFRunLoopSourceRef source;
const CFSocketContext context = {0,NULL,NULL,NULL,NULL};
_errorCode = NOERROR;
if((self.listenfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0) {
_errorCode = NOERROR;
}else{
memset(&servaddr,0,sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
if(bind(self.listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) {
_errorCode = BINDERROR;
}else{
if(listen(self.listenfd,LISTENQ)< 0){
_errorCode = LISTENERROR;
}else{
self.sRef = CFSocketCreateWithNative(NULL,self.listenfd,kCFSocketAcceptCallBack,acceptConnection,&context);
if(self.sRef == NULL) {
_errorCode = CFSOCKETCREATEERROR;
}else{
source = CFSocketCreateRunLoopSource(kCFAllocatorDefault,self.sRef,0) ;
CFRunLoopAddSource(CFRunLoopGetCurrent(),source,kCFRunLoopDefaultMode);
CFRelease(source);
CFRunLoopRun();
}
}
}
}
return self;
}
void acceptConnection(CFSocketRef sRef,CFSocketCallBackType cType,CFDataRef address,const void *data ,void * info) {
CFSocketNativeHandle csock = *(CFSocketNativeHandle*)data;
CFSocketRef sn;
CFRunLoopSourceRef source;
const CFSocketContext context = {0,NULL,NULL,NULL,NULL};
sn = CFSocketCreateWithNative(NULL,csock,kCFSocketDataCallBack,receiveData,&context);
source = CFSocketCreateRunLoopSource(NULL,sn,0);
CFRunLoopAddSource(CFRunLoopGetCurrent(),source,kCFRunLoopDefaultMode);
CFRelease(source);
CFRelease(sn);
return;
}
void receiveData(CFSocketRef sRef,CFSocketCallBackType cType,CFDataRef address,const void * data,void *info) {
CFDataRef df = (CFDataRef)data;
long len = CFDataGetLength(df);
if(len <= 0 )return ;
UInt8 buf[len];
CFRange range = CFRangeMake(0,len);
CFDataGetBytes(df,range,buf);
buf[len] = '\0';
NSString * str = [[NSString alloc]initWithData:(__bridge NSData*)data encoding:NSASCIIStringEncoding];
NSLog(@"Recieved: %@",str);
[[NSNotificationCenter defaultCenter] postNotificationName:@"posttext" object:str];
CFSocketSendData(sRef,address,df,0);//Echo back
}
@end
我想知道的是.m文件中的void acceptConnection(CFSocketRef sRef,CFSocketCallBackType cType,CFDataRef address,const void *data ,void * info) {...}是成员方法或者是是函数?其前面也没有加减号,以前从来么有见过。这东东是什么?能否补充下相关的知识,我的oc是自学的,求讲解下。谢谢各位大神!
+
이 없는-
은 C언어의 문법xcode를 혼합하여 사용할 수 있습니다