IOS Stream Socket

依然范特西╮ 提交于 2019-12-14 03:04:38

问题


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:


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! :)



来源:https://stackoverflow.com/questions/31068037/ios-stream-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!