iOS使用套接字连接发送数据

时间:2016-09-20 07:37:40

标签: ios objective-c iphone sockets tcp

我在iOS中实现了套接字连接。

我想要做的是将数据串发送到连接的设备...... (当有人发送到我的设备时,我能够接收数据) 我已经尝试过这段代码,但当我关闭我的应用程序时,数据会在其他设备上收到。

- (IBAction)connectToServer:(id)sender {

    NSLog(@"Setting up connection to %@ : %i", _ipAddressText.text, [_portText.text intValue]);
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef) _ipAddressText.text, [_portText.text intValue], &readStream, &writeStream);

    messages = [[NSMutableArray alloc] init];

    [self open];
}

- (void)open {

    NSLog(@"Opening streams.");

    outputStream = (__bridge NSOutputStream *)writeStream;
    inputStream = (__bridge NSInputStream *)readStream;

    [outputStream setDelegate:self];
    [inputStream setDelegate:self];

    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [outputStream open];
    [inputStream open];

    _connectedLabel.text = @"Connected";
}

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

    NSLog(@"stream event %lu", streamEvent);

    switch (streamEvent) {

        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            _connectedLabel.text = @"Connected";
            break;

        case NSStreamEventHasBytesAvailable:
            if (theStream == inputStream)
            {
                uint8_t buffer[1024];
                NSInteger 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 NSStreamEventHasSpaceAvailable:
            NSLog(@"Stream has space available now");
            break;

        case NSStreamEventErrorOccurred:
            NSLog(@"error: %@",[theStream streamError].localizedDescription);
            break;

        case NSStreamEventEndEncountered:
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            _connectedLabel.text = @"Disconnected";
            NSLog(@"close stream");
            break;

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

 /* Sends data to other device */
 - (IBAction) sendMessage {

    NSLog(@"sendMessage");
    NSString *response  = [NSString stringWithFormat:@"msg:%@", _dataToSendText.text];
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    NSLog(@"[data length] %lu",(unsigned long)[data length]);
    [outputStream write:[data bytes] maxLength:[data length]];

 }

我在哪里弄错了?

2 个答案:

答案 0 :(得分:3)

经过艰苦研究后,我发现在字符串消息末尾添加\n表示我的缓冲区已收到整个字符串。 现在开始发送文件,所以它有效......

要通过套接字发送字符串,必须标记字符串的结尾。即;添加\n

答案 1 :(得分:0)

要标记一个字符串开头和结尾的字符串,ASCII control characters这样做,八位字节为\002&分别为\003。我建议使用这些控制字符而不是仅添加换行符,您的文本可能会有换行符,这可能会产生问题。