简体   繁体   English

使用套接字的iOS到Linux连接

[英]iOS to linux connection using sockets

I want to connect iphone to my linux machine using sockets. 我想使用套接字将iPhone连接到我的Linux机器。 I ran server program on linux and kept socket in listening mode and tried to send string from my iphone. 我在Linux上运行服务器程序,并使套接字保持在侦听模式,并尝试从iPhone发送字符串。 But not able connect to linux machine. 但是无法连接到linux机器。 I tried CFStream api. 我尝试了CFStream API。 for connection i used port 3000 . 对于连接,我使用端口3000。 My code is as below: 我的代码如下:

- (void)viewDidLoad {

    [super viewDidLoad];

    NSLog(@"view did load");
    data = [[NSMutableData alloc] init];
    outputStream = [[NSOutputStream alloc] initToMemory];
    inputStream  = [[NSInputStream alloc] init];
    [self initNetworkCommunication];

    [self sendString:@"Hello World\n"]

}
- (void)initNetworkCommunication { 

     CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.62",3000, &readStream, &writeStream);

     inputStream = (__bridge NSInputStream *)(readStream); // ivar
    [inputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
   [inputStream open];

     outputStream = ( __bridge NSOutputStream *)(writeStream); // ivar
    [outputStream setDelegate:self];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream open];
}

-(void)sendString:(NSString *)string {

    NSLog(@"data string:%@",string);
    if(!CFWriteStreamOpen(writeStream)){
      NSLog(@"Error, writeStream not open");

     //[outputStream close];
    }
    NSLog(@"Status of outputStream: %i", [outputStream streamStatus]);

    NSData *data = [[NSData alloc] initWithData:[string dataUsingEncoding:NSASCIIStringEncoding]];

    [outputStream write:[data bytes] maxLength:[data length]];
}
-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

    NSLog(@"thestream:%@",theStream);
    NSLog(@"stream event %lu", (unsigned long)streamEvent);
    BOOL  byteIndex = nil;

    switch (streamEvent) {
        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            break;
        case NSStreamEventHasSpaceAvailable: {
            uint8_t *readBytes = (uint8_t *)[data mutableBytes];
            readBytes += byteIndex; // ivar
            int data_len = [data length];
            unsigned int len = ((data_len - byteIndex >= 1024) ? 1024 : (data_len - byteIndex));
            uint8_t buf [len];
            (void)memcpy(buf, readBytes, len);
            len = [(NSOutputStream *)theStream write:(const uint8_t *)buf maxLength:len];
            NSLog(@"Sending buffer of len: %d", len);
            byteIndex += len;
            break;
        }
        case NSStreamEventHasBytesAvailable:
            NSLog(@"the stream:%@, inputStream:%@",theStream,inputStream);
            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 sendString:@"Another Test"];
            }
               break;

        case NSStreamEventErrorOccurred:
            theError = [theStream streamError];
           NSString * event = [[NSString alloc]initWithFormat:@"NSStreamEventErrorOccurred %@ ",theError];
           NSLog(@"Can not connect to the host!:%@",event);
           break;
//        case NSStreamEventEndEncountered:
//            NSLog(@"Closing stream...");
//            [theStream close];
//            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//            //[theStream release];
//            theStream = nil;
//            break;
//        default:

//            NSLog(@"Unknown event");

    }
}

I got the solution. 我找到了解决方案。 I did some mistakes.Commenting two lines in view did load and adding two lines in initNetworkCommunication solved problem corrected code is as below. 我犯了一些错误。评论了两行以确保加载,并在initNetworkCommunication中添加了两行以解决问题更正的代码如下。

 - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"view did load"); data = [[NSMutableData alloc] init]; // outputStream = [[NSOutputStream alloc] initToMemory]; // Commented this two lines // inputStream = [[NSInputStream alloc] init]; [self initNetworkCommunication]; [self sendString:@"Hello World\\n"] } - (void)initNetworkCommunication { //My program stuck at CFStreamCreatePairWithSocketToHost. I declared this two objects globally but it didn't work then I declared it here now it works CFReadStreamRef readStream ; CFWriteStreamRef writeStream ; CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.62",3000, &readStream, &writeStream); inputStream = (__bridge NSInputStream *)(readStream); // ivar [inputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; outputStream = ( __bridge NSOutputStream *)(writeStream); // ivar [outputStream setDelegate:self]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream open]; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM