IOS Stream Socket

818 views Asked by At

I am working about socket using Stream

I used this code to connect to my server:

- (void)initNetworkCommunication {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"host", port, &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];
}

I connected success to server, but I cannot send text to server:

This is my code:

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

//    NSLog(@"stream event %i", streamEvent);

    switch (streamEvent) {

        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            break;
        case NSStreamEventHasBytesAvailable:

            if (theStream == inputStream) {

                uint8_t buffer[1024];
                int len;

                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {

                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                        if (nil != output) {

                            NSLog(@"server said: %@", output);
                            [self messageReceived:output];

                        }
                    }
                }
            }
            break;


        case NSStreamEventErrorOccurred:

            NSLog(@"Can not connect to the host!");
            break;

        case NSStreamEventEndEncountered:

            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            theStream = nil;

            break;
        default:
            NSLog(@"Unknown event");
    }

}

- (void) messageReceived:(NSString *)message {

}
- (IBAction) sendMessage {

    NSString *response  = [NSString stringWithFormat:@"msg:%@", inputMessageField.text];
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    [outputStream write:[data bytes] maxLength:[data length]];
    inputMessageField.text = @"";

}

When I click button Send it show 'Unknown event'

1

There are 1 answers

0
0yeoj On BEST ANSWER

I have a method for sending data in socket:

- (void)socketWriteWithData:(NSData *)data
{
    uint8_t *bytes = (uint8_t *)[data bytes];

    __block BOOL isSent = NO;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^ {
        isSent = ([outputStream write:bytes maxLength:[data length]] > 0);

        dispatch_async(dispatch_get_main_queue(), ^(void)
        {
            NSLog(!isSent ? @"Sending failed" : @"Sent");
        });
    });
}

Check this out, might be helpful to you..

Note: if the log says your data is sent, maybe the problem is in your server. Cheers! :)