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>];