I set socket connection in appdelegate from app starting up connecting to server. in appdelegate.h

@interface AppDelegate : NSObject <NSStreamDelegate,UIApplicationDelegate> {
    UIWindow *window;
    UITabBarController *tabBarController;
    NSInputStream *inputStream;
 NSOutputStream *outputStream;
}

then in appdelegate.m set connecting to server:

 CFReadStreamRef readStream;
 CFWriteStreamRef writeStream;
 CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"111.111.111.11", 111, &readStream, &writeStream);

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

It runs well when app startup. communicate well also.

and then I have a tab controller. Every one of tabs needs exchanged datas to server by this socket. I dont want to creat different socket for every tab.

How do I use the same outputstream/inputstream?

I try this in firstviewcontroall.m but failed:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSData *data = [[NSData alloc] initWithData:[@"hello this is firstview" dataUsingEncoding:NSUTF8StringEncoding]];
 [outputStream write:[data bytes] maxLength:[data length]];
}

There is no datas sending to server. I dont want to create a socket on every viewcontroller to server. that wastes too much resources. My question is how do I send/recieve datas by one socket connection?

有帮助吗?

解决方案

Use the streams by below way:

AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDel.outputStream write:[data bytes] maxLength:[data length]];
[appDel.inputStream <CALL_YOUR_METHOD>];

其他提示

I would create a utility/manager class to handle communication with the server. This way you can easily access that from other parts of your code. Also easy to make sure that it is thread safe. Note that you should consider not doing these on the main thread.

However, here is the code if you do want to access the variables defined in AppDelegate:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.outputStream <method>];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top