📄 tcpclient.m
字号:
/*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>#import "TCPClient.h"@implementation TCPClient@synthesize _callback;@synthesize _nstrName;- (id)init { return self;}- (void)dealloc { [self stop]; [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 TCPClientConnetCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { if (kCFSocketConnectCallBack == type) { // for an AcceptCallBack, the data parameter is a pointer to a CFSocketNativeHandle }}static void TCPClientDataCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { TCPClient* tcpClient = (TCPClient*)info; if (kCFSocketDataCallBack == type) { // for an AcceptCallBack, the data parameter is a pointer to a CFSocketNativeHandle [tcpClient recvData:socket Addr:address Data:data Info:(void*)info]; }}- (int)startClientWithName:(NSString*)name Addr:(NSString*)pAddr Port:(int)nPort CallBack:(void*)callback{ // save callback self._callback = [[iCallBack alloc] init]; [self._callback parseCallBack:callback]; self._nstrName = [NSString stringWithString:name]; CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL}; _ipv4socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketDataCallBack, (CFSocketCallBack)&TCPClientDataCallBack, &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 = inet_addr([pAddr UTF8String]); NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)]; if (kCFSocketSuccess != CFSocketConnectToAddress(_ipv4socket, (CFDataRef)address4, 100)){ if (_ipv4socket) CFRelease(_ipv4socket); _ipv4socket = NULL; return NO; } // send own name, means register iMsgBundle* bundle = [[iMsgBundle alloc] init]; iMsg* msg = [bundle bundleMsgWithMsgId:REGISTER_SERVER Dest:self._nstrName Body:nil]; if ([self sendMsgToServer:msg] < 0){ 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); return YES;}- (void)recvData:(CFSocketRef)s Addr:(CFDataRef)address Data:(const void*)data Info:(void*)info{ NSData* recv = (NSData*)data; // parse msg iMsgBundle* bundle = [[iMsgBundle alloc] init]; iMsg* _tagMsg; _tagMsg = [bundle unBundleMsgWithRecvData:recv]; if (!_tagMsg){ return; } // callback function iCommCallBack callback; callback = [self._callback findCallBackByMsgId:_tagMsg->_msgId]; callback(_tagMsg); [_tagMsg release]; [bundle release];}- (int)sendMsgToServer:(iMsg*)msg{ int nRet; if (!_ipv4socket){ return kCFSocketError; } iMsgBundle* bundle = [[iMsgBundle alloc] init]; msg->_s = _ipv4socket; NSData* data = [bundle unBundleMsgHeader:msg]; nRet = CFSocketSendData(msg->_s, nil, (CFDateRef)data, MSG_TIMEOUT); [bundle release]; [msg release]; return nRet;}- (int)stop { if (_ipv4socket) { CFSocketInvalidate(_ipv4socket); CFRelease(_ipv4socket); _ipv4socket = NULL; } return YES;}@end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -