CocoaAsyncSocket例子

施凡
2023-12-01

============================================================
博文原创,转载请声明出处
电子咖啡(原id蓝岩)
============================================================
在项目中用到了tcp/udp,写了个工具类,备忘,也算是对开源的一点贡献。

工程已经上传到github:https://github.com/ygweric/AsyncSocketbDemo


封装了工具类LocalSocketClient,内容如下,其中有些方法和变量是我的项目中用到了,阅读时你直接跳过就好了。

LocalSocketClient.h

@interface LocalSocketClient : NSObject<AsyncSocketDelegate,AsyncUdpSocketDelegate>
@property (retain,nonatomic) NSString* yunhoAddress;
@property int yunhoPort;

@property (retain,nonatomic)  AsyncSocket *socket;



@property (retain,nonatomic)     NSString* mIP;
@property int mPort;
@property BOOL isConnected;




+(LocalSocketClient*)share;
- (void) connectToHost;
- (void) connectToHost:(NSString*)host port:(int)port ;
- (void) disconnectTcp ;
-(void)sendSearchBroadcast;
-(void)sendToUDPServer:(NSString*) msg address:(NSString*)address port:(int)port;
- (void)sendMtalkMessage:(NSString*)ctalk_xml ;

@end


LocalSocketClient.m

#import "LocalSocketClient.h"

#define CTALK_SEARTH @"<ctalk id=\"%@\" xmlns=\"urn:xmpp:ctalk:1\"><search/></ctalk>"
#define CTALK_STANDARD_HEADER @"<ctalk id=\"%@\" xmlns=\"urn:xmpp:ctalk:1\">"
#define SOCKET_TIMEOUT -1 //当timeout,socket会断开
#define BCPORT 9001


@implementation LocalSocketClient{
@private

    
    
}
@synthesize isConnected;
@synthesize yunhoAddress;
@synthesize yunhoPort;

@synthesize socket;


@synthesize mIP;
@synthesize mPort;


static LocalSocketClient* localSocketClient;

+(LocalSocketClient*)share{
    if (localSocketClient==nil) {
        localSocketClient =[[LocalSocketClient alloc] init];
    }
    return localSocketClient;
}

-(id)init{
    if (self=[super init]) {
      
        
    }
    return self;
}

#pragma mark udp
-(void)sendSearchBroadcast{
    NSString* bchost=@"255.255.255.255";
    [self sendToUDPServer:[NSString stringWithFormat:CTALK_SEARTH,@"1231-12312-4214-234"] address:bchost port:BCPORT];
}
-(void)sendToUDPServer:(NSString*) msg address:(NSString*)address port:(int)port{
    AsyncUdpSocket *udpSocket=[[[AsyncUdpSocket alloc]initWithDelegate:self]autorelease];
    NSLog(@"---address:%@,port:%d,msg:%@",address,port,msg);
    //receiveWithTimeout is necessary or you won't receive anything
    [udpSocket receiveWithTimeout:10 tag:2]; //
    [udpSocket enableBroadcast:YES error:nil];
    NSData *data=[msg dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:data toHost:address port:port withTimeout:10 tag:1];
}
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
    NSString* rData= [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
                      autorelease];
    NSLog(@"onUdpSocket:didReceiveData:---%@",rData);


    return YES;
}
-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
    NSLog(@"didNotSendDataWithTag----");

    
}
-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{
    NSLog(@"didNotReceiveDataWithTag----");

}
-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
    NSLog(@"didSendDataWithTag----");

}
-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{
    NSLog(@"onUdpSocketDidClose----");
}


- (void) connectToHost{
    
    [self connectToHost:mIP port:mPort];
    
    
}

#pragma mark tcp
- (void) connectToHost:(NSString*)host port:(int)port {
    socket = [[AsyncSocket alloc] initWithDelegate:self];

    [socket disconnect];

    NSLog(@"tcp connecting to host:%@,port:%d",host,port);
    @try {
        [socket connectToHost:host onPort:port error:nil];
        [socket readDataWithTimeout:SOCKET_TIMEOUT tag:1];

    }
    @catch (NSException *exception) {
        NSLog(@"connect exception %@,%@", [exception name], [exception description]);

    }
}
- (void) disconnectTcp {
    if ([socket isConnected]) {
        [socket disconnect];
    }
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
    NSLog(@"did connect to host %@:%d", host, port);
    isConnected=YES;
    [NSThread detachNewThreadSelector:@selector(keepActivityST) toTarget:self withObject:nil];
    
}

-(void)keepActivityST{
    while (isConnected) {
        [NSThread sleepForTimeInterval:1];
        [self performSelectorOnMainThread:@selector(sendMessage:) withObject:@"" waitUntilDone:NO];
    }
}

-(void)onSocketDidDisconnect:(AsyncSocket *)sock{
    isConnected=NO;
    NSLog(@"onSocketDidDisconnect sock:%@",sock);

    
}

- (void)sendMtalkMessage:(NSString*)ctalk_xml {

    [self sendMessage:ctalk_xml];
}
- (void)sendMessage:(NSString*)msg {
    NSLog(@"tcp send msg:%@",  msg);
    [socket readDataWithTimeout:SOCKET_TIMEOUT tag:1];
    [socket writeData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:SOCKET_TIMEOUT tag:1];
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSString* message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease];
    NSLog(@"onSocket:didReadData msg:%@ ",message);
   }
-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
    NSLog(@"onSocket:shouldTimeout-ReadWithTag:-----------");
    return 0;
}
-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
    NSLog(@"onSocket:shouldTimeout-WriteWithTag:-----------");
    return 0;
}

-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"didWriteDataWithTag tag:%ld",tag);
}

#pragma mark other utils function


@end
 


ref:

CocoaAsyncSocket学习 | Marshal's Blog

基于 cocoaAsyncSocket socket 包装类 | Erlang program research

iphone开源网络编程cocoaasyncsocket - 随记 - 博客频道 - CSDN.NET

CocoaAsyncSocket使用笔记_收音机_百度空间



 类似资料: