无法通过IOS套接字发送消息

时间:2012-12-20 17:02:21

标签: ios objective-c

我正在使用CFStream构建一个IOS套接字客户端。我已设法连接到我的测试服务器并从中接收消息。问题是如果客户端发送消息服务器无法接收它,并且在该客户端没有从服务器接收任何消息。我的代码如下。可能有什么不对?

- (void)initCommunicationWithAddress:(NSString*) address withPort:(int) port
{
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)address, port, &readStream, &writeStream);

    self.inputStream = (__bridge_transfer NSInputStream *)readStream;
    self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;

    [self.inputStream setDelegate:self];
    [self.outputStream setDelegate:self];
    [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream open];
    [self.outputStream open];
    NSLog(@"Socket Init: %@", @"");
}

- (void)sendMessage:(NSString*)msg
{
    msg =  @"hello";
    NSLog(@"SendMessage: %@", msg);
    NSData *data = [[NSData alloc] initWithData:[msg dataUsingEncoding:NSASCIIStringEncoding]];
    [self.outputStream write:[data bytes] maxLength:[data length]];
}

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

    switch (streamEvent) {

        case NSStreamEventOpenCompleted:
            [self streamOpened];
            break;

        case NSStreamEventHasBytesAvailable:
            NSLog(@"Stream Bytes Available:%@", @"");
            if (theStream == self.inputStream) {

                NSMutableData* data = [NSMutableData data];
                uint8_t buffer[1024];
                int len;
                int bytesRead = 0;

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

                        [data appendBytes:(const void *)buffer length:len];
                        bytesRead = bytesRead + len;
                    }
                }

                NSString* output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

                if (nil != output) {
                    [self HandleServerMessage: output];

                }
            }
            break;

        case NSStreamEventErrorOccurred:
             NSLog(@"Stream Error:%@", @"");
            [self streamError];
            break;

        case NSStreamEventEndEncountered:
            NSLog(@"Stream Event End:%@", @"");
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [self streamEnd];
            break;

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

1 个答案:

答案 0 :(得分:1)

我发现了自己的错误。我应该等待NSStreamEventHasSpaceAvailable事件,或者在向服务器发送任何消息之前检查空间是否可用。