Skip to content

Instantly share code, notes, and snippets.

@hallski
Created May 6, 2012 22:46
Show Gist options
  • Save hallski/2624867 to your computer and use it in GitHub Desktop.
Save hallski/2624867 to your computer and use it in GitHub Desktop.
TCRACSocket with subjects
TCRACSocket *socket = [TCRACSocket new];
[[[socket connectToHost:@"localhost" port:1236] selectMany:^id<RACSubscribable>(id x) {
return [x lines];
}]
subscribeNext:^(id x) {
self.outputField.stringValue = x;
}
error:^(NSError *error) {
exit(0);
}];
#import "TCRACSocket.h"
#import <AsyncSocket.h>
@interface TCRACSocket ()
@property(strong,readwrite) AsyncSocket *sock;
@property(strong) RACSubject *connectSubject;
@property(strong) RACSubject *linesSubject;
@end
@implementation TCRACSocket
@synthesize sock = _sock;
@synthesize connectSubject = _connectSubject;
@synthesize linesSubject = _linesSubject;
-(id)init
{
if (!(self = [super init]))
return nil;
_sock = [[AsyncSocket alloc] initWithDelegate:self];
_linesSubject = [RACSubject subject];
_connectSubject = [RACAsyncSubject subject];
return self;
}
- (RACSubject *)connectToHost:(NSString *)host port:(int)port
{
NSError *err = nil;
if(![self.sock connectToHost:host onPort:port error:&err])
[self.connectSubject sendError:err];
return self.connectSubject;
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err;
{
if (err) {
[self.linesSubject sendError:err];
} else {
[self.linesSubject sendCompleted];
}
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port;
{
[self.connectSubject sendNext:self];
[self.connectSubject sendCompleted];
[self.sock readDataToData:[AsyncSocket LFData] withTimeout:-1 tag:0];
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self.linesSubject sendNext:s];
[self.sock readDataToData:[AsyncSocket LFData] withTimeout:-1 tag:0];
}
- (RACSubscribable *)lines;
{
return self.linesSubject;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment