我正在尝试编写一个应用程序来通过 CocoaAsyncSocket 库发送/接收数据。
在应用程序的第一个版本中,套接字在 View Controller 中创建/初始化,我还将正确调用的委托方法放置在其中:
WakmanFirstViewController.m
#import "WakmanFirstViewController.h"
#import "GCDAsyncSocket.h"
@implementation WakmanFirstViewController
- (void)viewDidLoad
{
[super viewDidLoad];
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![asyncSocket connectToHost:@"192.168.1.13" onPort:2000 error:&error]) {
NSLog(@"Unable to connect to due to invalid configuration: %@",error);
}
NSData *requestData = [@"C" dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:requestData withTimeout:-1.0 tag:0];
[asyncSocket readDataWithTimeout:1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@"socket:didConnectToHost:%@ port:%hu", host, port);
}
... (other delegate methods)
现在我正在尝试从 ViewController 中删除套接字的创建并将其放入 Singleton 类中,以便我也可以从其他视图中使用相同的连接。
为此,我创建了一个新类(SocketConnection),其中还移动了委托方法:
wakmanSocketConnection.h
#import <Foundation/Foundation.h>
#import "GCDAsyncSocket.h"
@interface SocketConnection : NSObject {
}
+ (GCDAsyncSocket *)getInstance;
@end
wakmanSocketConnection.m
#import "SocketConnection.h"
static GCDAsyncSocket *socket;
@implementation SocketConnection
+ (GCDAsyncSocket *)getInstance
{
@synchronized(self) {
if (socket == nil) {
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
if (![socket isConnected]) {
NSError *error = nil;
if (![socket connectToHost:@"192.168.1.13" onPort:2000 error:&error]){
NSLog(@"Error connecting: %@", error);
}
}
}
return socket;
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@"socket connected");
}
... (other delegate methods)
然后我修改了 Viewcontroller:
WakmanFirstViewController.h
#import <UIKit/UIKit.h>
#import "SocketConnection.h"
@class GCDAsyncSocket;
@interface WakmanFirstViewController : UIViewController {
GCDAsyncSocket *socket;
}
@end
WakmanFirstViewController.m
#import "WakmanFirstViewController.h"
@implementation WakmanFirstViewController
- (void)viewDidLoad
{
[super viewDidLoad];
socket = [SocketConnection getInstance];
NSData *requestData = [@"C" dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:requestData withTimeout:-1.0 tag:0];
[asyncSocket readDataWithTimeout:1 tag:0];
}
连接已建立,但问题是未调用委托方法。
在wakmanSocketConnection.m 中,我将委托设置为 self,因此它应该引用我复制方法的类。
有人可以帮我找到问题吗?
谢谢, 科拉多