tcpserver.m
来自「使用CFNetwork.framework实现的通信中间件。」· M 代码 · 共 290 行
M
290 行
/*File: TCPServer.mAbstract: A TCP server that listens on an arbitrary port.Version: 1.5Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.("Apple") in consideration of your agreement to the following terms, and youruse, installation, modification or redistribution of this Apple softwareconstitutes acceptance of these terms. If you do not agree with these terms,please do not use, install, modify or redistribute this Apple software.In consideration of your agreement to abide by the following terms, and subjectto these terms, Apple grants you a personal, non-exclusive license, underApple's copyrights in this original Apple software (the "Apple Software"), touse, reproduce, modify and redistribute the Apple Software, with or withoutmodifications, in source and/or binary forms; provided that if you redistributethe Apple Software in its entirety and without modifications, you must retainthis notice and the following text and disclaimers in all such redistributionsof the Apple Software.Neither the name, trademarks, service marks or logos of Apple Inc. may be usedto endorse or promote products derived from the Apple Software without specificprior written permission from Apple. Except as expressly stated in this notice,no other rights or licenses, express or implied, are granted by Apple herein,including but not limited to any patent rights that may be infringed by yourderivative works or by other works in which the Apple Software may beincorporated.The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NOWARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIEDWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR INCOMBINATION WITH YOUR PRODUCTS.IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTEGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/ORDISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OFCONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IFAPPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Copyright (C) 2008 Apple Inc. All Rights Reserved.*/#include <sys/socket.h>#include <netinet/in.h>#include <unistd.h>#include <CFNetwork/CFSocketStream.h>#import "TCPServer.h"@implementation TCPServer@synthesize _arrayClient, _callback;- (id)init { return self;}- (void)dealloc { [self._arrayClient release]; [self._callback release]; [super dealloc];}// This function is called by CFSocket when a new connection comes in.// We gather some data here, and convert the function call to a method// invocation on TCPServer.static void TCPServerAcceptCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { TCPServer *server = (TCPServer *)info; if (kCFSocketAcceptCallBack == type) { // for an AcceptCallBack, the data parameter is a pointer to a CFSocketNativeHandle CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data; CFSocketContext socketCtxt = {0, server, NULL, NULL, NULL}; CFSocketRef acceptSocket = CFSocketCreateWithNative(kCFAllocatorDefault, nativeSocketHandle, kCFSocketDataCallBack, (CFSocketCallBack)&DataCallBack, &socketCtxt); // set up the run loop sources for the sockets CFRunLoopRef cfrl = CFRunLoopGetCurrent(); CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, acceptSocket, 0); CFRunLoopAddSource(cfrl, source, kCFRunLoopCommonModes); CFRelease(source); // save sokcet info server->_acceptSocket = acceptSocket; server->_handle = nativeSocketHandle; }}static void DataCallBack ( CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef address, const void *data, void *info ){ TCPServer* server = (TCPServer*)info; switch (callbackType) { case kCFSocketDataCallBack: [server recvData:s Addr:address Data:data Info:(void*)info]; break; default: break; }}- (int)startServerWithPort:(int)nPort CallBack:(void*)callback{ // save callback self._arrayClient = [NSMutableArray array]; self._callback = [[iCallBack alloc] init]; [self._callback parseCallBack:callback]; CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL}; _ipv4socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&TCPServerAcceptCallBack, &socketCtxt); if (NULL == _ipv4socket) { if (_ipv4socket) CFRelease(_ipv4socket); _ipv4socket = NULL; return NO; } int yes = 1; setsockopt(CFSocketGetNative(_ipv4socket), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); // set up the IPv4 endpoint; use port 0, so the kernel will choose an arbitrary port for us, which will be advertised using Bonjour struct sockaddr_in addr4; memset(&addr4, 0, sizeof(addr4)); addr4.sin_len = sizeof(addr4); addr4.sin_family = AF_INET; addr4.sin_port = nPort; addr4.sin_addr.s_addr = htonl(INADDR_ANY); NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)]; if (kCFSocketSuccess != CFSocketSetAddress(_ipv4socket, (CFDataRef)address4)) { if (_ipv4socket) CFRelease(_ipv4socket); _ipv4socket = NULL; return NO; } // set up the run loop sources for the sockets CFRunLoopRef cfrl = CFRunLoopGetCurrent(); CFRunLoopSourceRef source4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _ipv4socket, 0); CFRunLoopAddSource(cfrl, source4, kCFRunLoopCommonModes); CFRelease(source4); // if is command line application, running loop is essential.#ifdef _Server_CommandLine_App_ CFRunLoopRun();#endif return YES;}- (int)stop { if (_ipv4socket) { CFSocketInvalidate(_ipv4socket); CFRelease(_ipv4socket); _ipv4socket = NULL; } return YES;}- (void)recvData:(CFSocketRef)s Addr:(CFDataRef)address Data:(const void*)data Info:(void*)info{ TCPServer* server = (TCPServer*)info; NSData* recv = (NSData*)data; // parse msg iMsgBundle* bundle = [[iMsgBundle alloc] init]; iMsg* _tagMsg; _tagMsg = [bundle unBundleMsgWithRecvData:recv]; if (!_tagMsg){ return; } // save client's socket _tagMsg->_socClient = s; // if user register to server if ([_tagMsg->_msgId compare:REGISTER_SERVER] == NSOrderedSame){ iClientInfo* tag = [[iClientInfo alloc] init]; tag->_s = server->_acceptSocket; tag->_handle = server->_handle; tag._identifier = [NSString stringWithString:_tagMsg->_msgDest]; [server._arrayClient addObject:(id)tag]; [tag release]; return; } // if (!_tagMsg->_msgDest){ // reply, find CFSocket object by current socket// CFSocketRef socket = [self findAcceptSocketByClientSoc:s];// _tagMsg->_s = socket;// }// else{ // transfer, find CFSocket object by specific user// CFSocketRef socket = [self findAcceptSocketByDestName:_tagMsg->_msgDest];// _tagMsg->_s = socket;// } // find callback function iCommCallBack callback; callback = [self._callback findCallBackByMsgId:_tagMsg->_msgId]; callback(_tagMsg); [_tagMsg release]; [iMsgBundle release];}- (CFSocketRef)findAcceptSocketByClientSoc:(CFSocketRef)s{ int nCount = [self._arrayClient count]; iClientInfo* tagClient; CFSocketNativeHandle handle = CFSocketGetNative(s); for (int i = 0; i < nCount; i++){ tagClient = [self._arrayClient objectAtIndex:i]; if (handle == tagClient->_handle){ return tagClient->_s; } } return nil;}- (CFSocketRef)findAcceptSocketByDestName:(NSString*)destName{ int nCount = [self._arrayClient count]; iClientInfo* tagClient; for (int i = 0; i < nCount; i++){ tagClient = [self._arrayClient objectAtIndex:i]; if ([destName compare:tagClient._identifier] == NSOrderedSame){ return tagClient->_s; } } return nil;}- (iClientInfo*)findClientInfoByClientSoc:(CFSocketRef)s{ int nCount = [self._arrayClient count]; iClientInfo* tagClient; CFSocketNativeHandle handle = CFSocketGetNative(s); for (int i = 0; i < nCount; i++){ tagClient = [self._arrayClient objectAtIndex:i]; if (handle == tagClient->_handle){ return tagClient; } } return nil;}// server response sender.//- (int)replyMsgToSender:(iMsg*)msg{// int nRet;// nRet = [self sendMsg:msg];// return nRet;//}////// server transmit or send message to receiver.//- (int)sendMsgToReceiver:(iMsg*)msg{// CFSocketRef socket = [self findAcceptSocketByDestName:msg->_msgDest];// msg->_s = socket;// int nRet;// nRet = [self sendMsg:msg];// return nRet;//}- (int)sendMsgToClient:(iMsg*)msg{ CFSocketRef socket; if (msg->_msgDest){ socket = [self findAcceptSocketByDestName:msg->_msgDest]; } else { socket = [self findAcceptSocketByClientSoc:msg->_socClient]; } msg->_s = socket; // send message int nRet; nRet = [self sendMsg:msg]; return nRet;}- (int)sendMsg:(iMsg*)msg{ iMsgBundle* bundle = [[iMsgBundle alloc] init]; NSData* data = [bundle unBundleMsgHeader:msg]; int nRet = CFSocketSendData(msg->_s, nil, (CFDateRef)data, MSG_TIMEOUT); [bundle release]; return nRet;}@end
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?