我在NSObject类中实现GCDAsyncSocket委托,然后在viewController中调用它。 在运行它时,我找到了'didConnectToHost'和' didWriteDataWithTag'被称为,但我没有看到'didReadData'调用。这是我的代码:
SocketUtils.h
@interface SocketUtils : NSObject <GCDAsyncSocketDelegate>
@property (nonatomic) void (^SocketCallback)(id data);
@property (nonatomic) NSString *message;
@property (nonatomic) UIViewController *vc;
+ (SocketUtils *) createSocket:(NSString *)message inViewController:(UIViewController *)vc;
- (void) connectToSocket;
@end
SocketUtils.m
@implementation SocketUtils{
GCDAsyncSocket *socket;
}
+ (SocketUtils *) createSocket:(NSString *)message inViewController:(UIViewController *)vc{
SocketUtils *this = [[self alloc] init];
this.message = message;
[this connectToSocket];
return this;
}
- (void)connectToSocket{
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![socket connectToHost:SOCKET_IP onPort:[SOCKET_PORT intValue] error:&err])
{
NSLog(@"err: %@", [err localizedDescription]);
if(err){
[Utils showErrorDialog:[err localizedDescription] atViewController:_vc];
}
return;
}
}
#pragma mark - Socket delegate
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"Cool,didConnectToHost: %@", host);
[socket writeData:[_message dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
[socket readDataWithTimeout:-1 tag:0];
NSLog(@"didWriteDataWithTag: %ld", tag);
}
- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
NSLog(@"didReadData : %@", data);
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
_SocketCallback(msg);
}
- (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock{
NSLog(@"socketDidCloseReadStream");
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
NSLog(@"disconnected to socket: %@", err);
[Utils showErrorDialog:[err localizedDescription] atViewController:_vc];
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
NSLog(@"Accepted new socket from %@:%hu", [newSocket connectedHost], [newSocket connectedPort]);
}
然后在viewController中我调用:
socketUtils = [SocketUtils createSocket:@"GET_BOARD_CODE" inViewController:self];
socketUtils.SocketCallback = ^(id data) {
doSth();
};
我预测的第一件事就是破坏这个类,但是我试图保持所有@property =强,但不行。
有人可以帮忙吗?
答案 0 :(得分:0)
经过多次搜索,我意识到我忘了将“\ r \ n”附加到邮件中。 Okey只需将1行代码更改为:
this.message = [message stringByAppendingString:@"\r\n"];
它按预期工作。