IOS 流套接字

IOS Stream Socket

我正在使用 Stream 处理套接字

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

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

}

当我点击发送按钮时显示 'Unknown event'

我有一个在套接字中发送数据的方法:

- (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");
        });
    });
}

看看这个,可能对你有帮助..

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