0

首先 - 我是 iOS 6 编程的新手。我试图在应用程序启动时打开与远程服务器的套接字连接,并在某个后台线程中运行它。我有一个类 - NetworkCommunication.h,和 3 个视图控制器,我希望它们能够读取和写入流。

编码:

网络通讯.h:

#import <Foundation/Foundation.h>

@interface NetworkCommunication : NSObject {
   NSInputStream* inputStream;
   NSOutputStream* outputStream;
}

@property(retain) NSInputStream *inputStream;
@property(retain) NSOutputStream *outputStream;

-(void) initNetworkCommunication;

@end

网络通讯.m

#import "NetworkCommunication.h"

NSOutputStream *outputStream;
NSInputStream *inputStream;

@implementation NetworkCommunication

@synthesize outputStream;
@synthesize inputStream;

- (id) init {
    NSLog(@"Start!");
    [self initNetworkCommunication];
    return 0;
}

- (void)initNetworkCommunication {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", 7000, &readStream, &writeStream);



inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode ];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];


[inputStream open];
[outputStream open];


[inputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
                  forKey:NSStreamSocketSecurityLevelKey];
[outputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
                   forKey:NSStreamSocketSecurityLevelKey];

NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
                          [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
                          [NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
                          [NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
                          kCFNull,kCFStreamSSLPeerName,
                          nil];

CFReadStreamSetProperty((CFReadStreamRef)inputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
CFWriteStreamSetProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);

//[outputStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey];

NSString *response  = @"HELLO from my iphone\n";
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}


@end

我尝试在任何控制器或 main.m 中使用以下命令启动它: NetworkController *comm = [NetworkController new];

当它到达此代码时:

[inputStream open];
[outputStream open];

我得到“头 1:EXC_BAD_ACCESS(代码=1,地址=0x10917df0)”

我不知道如何使它工作。我想在应用程序启动时启动一个线程,并且能够写入 NSOutputStream 并从任何控制器读取 NSInputStream。可能吗?如果是这样,怎么做?

提前致谢

4

1 回答 1

0

我把你的代码和测试。当我-(id) init像你一样定义方法时,我遇到了同样的错误。但在这样改变之后:

NetworkCommunication的.h

   #import <Foundation/Foundation.h>

    @interface NetworkCommunication : NSObject<NSStreamDelegate>
    {
        NSInputStream* inputStream;
        NSOutputStream* outputStream;
        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
    }
    @property(retain) NSInputStream *inputStream;
    @property(retain) NSOutputStream *outputStream;
-(id)init;
    @end

NetworkCommunication的.m

#import "NetworkCommunication.h"

@implementation NetworkCommunication
@synthesize inputStream,outputStream;
-(id)init
{
    self=[super init];
    if (self) {
        NSLog(@"Start!");
        [self initNetworkCommunication];

    }
    return self;//you returned 0 but types not matched.
}
- (void)initNetworkCommunication {



    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", 7000, &readStream, &writeStream);



    inputStream = (__bridge_transfer NSInputStream *)readStream;
    outputStream = (__bridge_transfer NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode ];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];


    [inputStream open];
    [outputStream open];


 //   [inputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
  //                    forKey:NSStreamSocketSecurityLevelKey];
  //  [outputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
  //                     forKey:NSStreamSocketSecurityLevelKey];

//    NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
//                              [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
 //                             [NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
  //                            [NSNumber numberWithBool:NO], //kCFStreamSSLValidatesCertificateChain,
     //                         kCFNull,kCFStreamSSLPeerName,
    //                          nil];

//    CFReadStreamSetProperty((CFReadStreamRef)inputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
//    CFWriteStreamSetProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);

    //[outputStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey];

    NSString *response  = @"HELLO from my iphone\n";
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    [outputStream write:[data bytes] maxLength:[data length]];
}
@end

在我的视图控制器中,我像这样创建它

#import "ViewController.h"
#import "NetworkCommunication.h"
BOOL count;

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
        [super viewDidLoad];

    NetworkCommunication * nc=[[NetworkCommunication alloc] init];  
}

处理事件和查看错误

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
    NSLog(@"Stream triggered.");
    switch(event) {
            case NSStreamEventErrorOccurred:
        {

            NSLog(@"%@",[stream streamError].localizedDescription);

        }
            break;
        case NSStreamEventHasSpaceAvailable: {
            if(stream == outputStream) {
                NSLog(@"outputStream is ready.");
            }
            break;
        }
        case NSStreamEventHasBytesAvailable: {
            if(stream == inputStream) {
                NSLog(@"inputStream is ready.");
                uint8_t buf[1024];
                unsigned int len = 0;
                len = [inputStream read:buf maxLength:1024];
                if(len > 0) {
                    NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
                    [data appendBytes: (const void *)buf length:len];
                    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    [self readIn:s];
                }
            }
            break;
        }
        default: {
            NSLog(@"Stream is sending an Event: %i", event);
            break;
        }
    }
}

- (void)readIn:(NSString *)s {
    NSLog(@"Reading in the following:");
    NSLog(@"%@", s);
}

- (void)writeOut:(NSString *)s {
    uint8_t *buf = (uint8_t *)[s UTF8String];
    [outputStream write:buf maxLength:strlen((char *)buf)];
    NSLog(@"Writing out the following:");
    NSLog(@"%@", s);
}

当我尝试使用您的代码时。拒绝连接。所以我想问题出在你的IP地址上试试另一个。

于 2013-03-29T11:40:38.933 回答