无法通过IOS建立Socket连接

时间:2013-12-10 20:24:07

标签: ios objective-c sockets tcp

我第一次写一个IOS应用程序。它应该连接到静态IP设备,并向其发送某些“已知”命令。但由于某种原因,我无法建立连接。

Bellow是我用来建立连接和将数据写入端口的函数。

-(void)connection//:(NSString *)serviceName forIpAddress:(NSString *)ipAddress forPort:(NSString *)portNo
{
    if(input && output)
        [self close];
    NSString *urlString = [NSString stringWithFormat:@"%.%.%.%", "192.168.3.120"];
    NSURL *website = [NSURL URLWithString:urlString];
    if (!website) {
        NSLog(@"%@ is not a valid URL", website);
    }

    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)[website host], 43, &readStream, &writeStream);
    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    NSInputStream *input = (__bridge NSInputStream *)readStream;
    NSOutputStream *output= (__bridge NSOutputStream *)writeStream;
}



    - (void)open {
    [input setDelegate:self];
    [output setDelegate:self];
    [input scheduleInRunLoop:[NSRunLoop currentRunLoop]
                     forMode:NSDefaultRunLoopMode];
    [output scheduleInRunLoop:[NSRunLoop currentRunLoop]
                      forMode:NSDefaultRunLoopMode]; [input open];
    [output open];
}




-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
    NSString *event;
    switch (streamEvent)
    {
        case NSStreamEventNone:
            event = @"NSStreamEventNone";
            break;
        case NSStreamEventOpenCompleted:
            event = @"NSStreamEventOpenCompleted";
            break;
        case NSStreamEventHasBytesAvailable:
            event = @"NSStreamEventHasBytesAvailable";
            if (theStream == input)
            {
                uint8_t buffer[1024];
                NSInteger len;
                while ([input hasBytesAvailable])
                {
                    len = [input read:buffer maxLength:1024];
                    if (len > 0)
                    {
                            NSMutableString *output = [[NSMutableString alloc]initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];                                                       NSLog(@"Received data--------------------%@", output);
                    }
                }
            }
                                        break;
                                        case NSStreamEventHasSpaceAvailable:
                                        event = @"NSStreamEventHasSpaceAvailable";
                                        break;
                                        case NSStreamEventErrorOccurred:
                                        event = @"NSStreamEventErrorOccurred";
                                        //[self close];
                                        break;
                                        case NSStreamEventEndEncountered:
                                        break; default:
                                        event = @"NSStreamEventEndEncountered";
                                        //[self close];
                                        event = @"Unknown"; break;
    }
    NSLog(@"event------%@",event);
}



- (void)close
{
    [input close];
    [output close];
    [input removeFromRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];
    [output removeFromRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];
    [input setDelegate:nil];
    [output setDelegate:nil];
    input = nil;
    output = nil;
}




- (void)dataSending:(NSString*)data
{
    if(output)
    {
        if(![output hasSpaceAvailable])
            return;
        NSData *_data=[data dataUsingEncoding:NSUTF8StringEncoding];
        NSInteger data_len = [_data length];
        uint8_t *readBytes = (uint8_t *)[_data bytes];
        int byteIndex=0;
        unsigned int len=0;
        while (TRUE)
        {
            len = ((data_len - byteIndex >= 40960) ? 40960 : (data_len-byteIndex));
            if(len==0)
                break;
            uint8_t buf[len];
            (void)memcpy(buf, readBytes, len);
            len = [output write:(const uint8_t *)buf maxLength:len];
            byteIndex += len;
            readBytes += len;
        }
        NSLog(@"Sent data----------------------%@",data);
    }
}

我通过该代码将所提到的函数称为测试,没有任何反应

- (IBAction)pumpchange:(id)sender {
    [self connection];
    [self open];

    if ([self.pump backgroundImageForState:(UIControlStateNormal)]==[UIImage imageNamed:@"PumpOff.png"])
    {
        [self.pump setBackgroundImage:[UIImage imageNamed:@"PumpOn.png"] forState:(UIControlStateNormal)];
        [self dataSending:@"pump_on"];
    }

    else //if ([self.pump backgroundImageForState:(UIControlStateNormal)]==[UIImage imageNamed:@"PumpOn.png"])
    {
        [self.pump setBackgroundImage:[UIImage imageNamed:@"PumpOff.png"] forState:(UIControlStateNormal)];
        [self dataSending:@"pump_off"];
    }
    [self close];
}

先谢谢

1 个答案:

答案 0 :(得分:3)

似乎存在一些误解格式字符串如何工作,因为

NSString *urlString = [NSString stringWithFormat:@"%.%.%.%", "192.168.3.120"];

只为您提供字符串@"..."。也许你的意思是

NSString *urlString = [NSString stringWithFormat:@"%d.%d.%d.%d", 192, 168, 3, 120];

NSString *urlString = [NSString stringWithFormat:@"%s", "192.168.3.120"];

但你根本不需要格式字符串:

NSString *urlString = @"192.168.3.120";