IOS Stream Socket

时间:2015-06-26 08:02:38

标签: ios objective-c sockets nsstream

我正在使用Stream

来处理socket

我使用此代码连接到我的服务器:

- (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];
}

我将成功连接到服务器,但我无法将文本发送到服务器:

这是我的代码:

- (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 = @"";

}

当我点击按钮发送它时显示'未知事件'

1 个答案:

答案 0 :(得分:1)

我有一种在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");
        });
    });
}

检查一下,可能对你有帮助..

注意:如果日志显示您的数据已发送,则可能是服务器中存在问题。干杯! :)