如下所示是.h檔。 “對象-c
typedef NS_ENUM(NSUInteger,BSDServerErrorCode) {
沒有錯誤,
套接字錯誤,
BINDERROR,
監聽器錯誤,
CFSOCKETCREATEERROR,
接受錯誤
};
@interface BIDCFSocketServer:NSObject
@property(非原子)CFSocketRef sRef;
@property (非原子) int Listenfd, errorCode;
-(instancetype)initOnPort:(int)埠;
@結束
如下圖程式碼所示是.m檔;
「對象-c
#定義監聽 1024
@實作BIDCFSocketServer
-(實例類型)initOnPort:(int)連接埠{
struct sockaddr_in servaddr;
CFRunLoopSourceRef 來源;
const CFSocketContext context = {0,NULL,NULL,NULL,NULL};
_錯誤代碼=無錯誤;
if((self.listenfd = 套接字(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0) {
_錯誤代碼=無錯誤;
}別的{
memset(&servaddr,0,servaddr 大小);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(埠);
if(bind(self.listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) {
_errorCode = BINDERROR;
}別的{
if(聽(self.listenfd,LISTENQ)<0){
_errorCode = 監聽器;
}別的{
self.sRef = CFSocketCreateWithNative(NULL,self.listenfd,kCFSocketAcceptCallBack,acceptConnection,&context);
if(self.sRef == NULL) {
_errorCode = CFSOCKETCREATEERROR;
}別的{
源 = CFSocketCreateRunLoopSource(kCFAllocatorDefault,self.sRef,0) ;
CFRunLoopAddSource(CFRunLoopGetCurrent(),源,kCFRunLoopDefaultMode);
CFRelease(來源);
CFRunLoopRun();
}
}
}
}
返回自我;
}
void AcceptConnection(CFSocketRef sRef,CFSocketCallBackType cType,CFDataRef 位址,const void *data ,void * info) {
CFSocketNativeHandle csock = *(CFSocketNativeHandle*)data;
CFSocketRef sn;
CFRunLoopSourceRef 來源;
const CFSocketContext context = {0,NULL,NULL,NULL,NULL};
sn = CFSocketCreateWithNative(NULL,csock,kCFSocketDataCallBack,receiveData,&context);
來源 = CFSocketCreateRunLoopSource(NULL,sn,0);
CFRunLoopAddSource(CFRunLoopGetCurrent(),源,kCFRunLoopDefaultMode);
CFRelease(來源);
CFRelease(sn);
返回;
}
void receiveData(CFSocketRef sRef,CFSocketCallBackType cType,CFDataRef 位址,const void * data,void *info) {
CFDataRef df = (CFDataRef)資料;
長長度 = CFDataGetLength(df);
if(len <= 0 )返回 ;
UInt8 buf[len];
CFRange 範圍 = CFRangeMake(0,len);
CFDataGetBytes(df,範圍,buf);
buf[長度] = '\0';
NSString * str = [[NSString alloc]initWithData:(__bridge NSData*)資料編碼:NSASCIIStringEncoding];
NSLog(@"已收到:%@",str);
[[NSNotificationCenter defaultCenter] postNotificationName:@"posttext" 物件:str];
CFSocketSendData(sRef,address,df,0);//回顯
}
@結尾
我想知道是.m檔案中的void receiveConnection(CFSocketRef sRef,CFSocketCallBackType cType,CFDataRef address,const void *data ,void * info) {...}是成員方法還是函數?減號,以前從來沒有見過。