Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 96 lines (76 sloc) 2.315 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
//
// CBAbstractClient.m
// CubicusDraw
//
// Created by James Potter on 26/02/2012.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CBAbstractClient.h"

@implementation CBAbstractClient

@synthesize host;
@synthesize socket;
@synthesize writer;
@synthesize parser;
@synthesize connected;

- (id)initWithHost:(CBHost *)theHost
{
    self = [super init];
    if (self) {
        host = theHost;
        socket = [[AsyncSocket alloc] initWithDelegate:self];
        writer = [[SBJsonWriter alloc] init];
        parser = [[SBJsonParser alloc] init];
        connected = NO;
    }
    return self;
}

- (void)connect
{
    NSLog(@"Connecting...");
    NSError *err;
    if (![self.socket connectToHost:self.host.address
                        onPort:[self.host.port intValue]
                              error:&err]) {
        NSLog(@"Connect failed with error: %@", err);
    }

}

#pragma mark -
#pragma mark Helper methods

- (void)sendMessage:(NSString *)type content:(id)obj
{
    [self sendMessage:type content:obj tag:CBAbstractClientTagMessage];
}

- (void)sendMessage:(NSString *)type content:(id)obj tag:(long)tag
{
    NSLog(@"sendMessage: %@", type);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          type, @"type", obj, @"content", nil];
    NSString *msg = [NSString stringWithFormat:@"%@\r\n", [self.writer stringWithObject:dict]];
    
    // TODO: tag?
    [self.socket writeData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:tag];
}

- (void)readMessage
{
    // Read up to CRLF delimiter i.e. end of message
    [self.socket readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:CBAbstractClientTagMessage];
}

#pragma mark -
#pragma mark AsyncSocketDelegate

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"onSocketDidDisconnect called (failed to connect?)");
    self.connected = NO;
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"didConnect!");
    self.connected = YES;
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{

}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSAssert(tag == CBAbstractClientTagMessage, @"Expecting a message");
}

@end
Something went wrong with that request. Please try again.