简体   繁体   English

未调用AsyncSocket委托方法

[英]AsyncSocket delegate method not called

I retain a socket in a singleton class like following: 我在单例类中保留一个套接字,如下所示:

SocketConnection.h SocketConnection.h

@interface SocketConnection : NSObject

+ (GCDAsyncSocket *) getInstance;

@end

SocketConnection.m 套接字连接

#define LOCAL_CONNECTION 1

#if LOCAL_CONNECTION
#define HOST @"localhost"
#define PORT 5678
#else
#define HOST @"foo.abc"
#define PORT 5678
#endif

static GCDAsyncSocket *socket;

@implementation SocketConnection

+ (GCDAsyncSocket *)getInstance
{
    @synchronized(self) {
        if (socket == nil) {
            dispatch_queue_t mainQueue = dispatch_get_main_queue();
            socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
        }
        if (![socket isConnected]) {

            NSString *host = HOST;
            uint16_t port = PORT;
            NSError *error = nil;

            if (![socket connectToHost:host onPort:port error:&error])
            {
                NSLog(@"Error connecting: %@", error);
            }
        }
    }

    return socket;
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"socket connected");
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"socketDidDisconnect:%p withError: %@", sock, err);
}

@end

And in a viewController: 并在viewController中:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socket = [SocketConnection getInstance];
    }
    return self;
}

I can see that the socket is connected in my server, but there is nothing in my xcode console log. 我可以看到套接字已在服务器中连接,但是xcode控制台日志中没有任何内容。 Please help to see why it cannot invoke the delegate method? 请帮忙看看为什么它不能调用委托方法?

You are initializing the socket in SocketConnection's getInstance method, at which point you set the delegate to self . 您正在SocketConnection的getInstance方法中初始化套接字,此时将委托设置为self self refers to the SocketConnection instance, not your view controller. self是指SocketConnection实例,而不是您的视图控制器。 Either initialize the socket in the view controller (at which point it's not a singleton anymore), or create a delegate property on SocketConnection and pass delegate methods on to SocketConnection's delegate. 可以在视图控制器中初始化套接字(此时不再是单例),或者在SocketConnection上创建一个委托属性,然后将委托方法传递给SocketConnection的委托。 Personally, I do the latter, but I send out notifications as opposed to delegate messages. 就个人而言,我会执行后者,但我会发出通知而不是委托消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM