我在app中设置了套接字连接,从app启动到连接到服务器。在appdelegate.h中
@interface AppDelegate : NSObject <NSStreamDelegate,UIApplicationDelegate> {
UIWindow *window;
UITabBarController *tabBarController;
NSInputStream *inputStream;
NSOutputStream *outputStream;
}然后在appdelegate.m集合中连接到服务器:
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];它在应用程序启动时运行良好。也能很好地沟通。
然后我有了一个标签控制器。每个标签都需要通过该套接字与服务器交换数据。我不想为每个标签创建不同的套接字。
如何使用相同的outputstream/inputstream?
我在firstviewcontroall.m .m中尝试了一下,但失败了:
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *data = [[NSData alloc] initWithData:[@"hello this is firstview" dataUsingEncoding:NSUTF8StringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}没有数据发送到服务器。我不想在每个视图控制器上创建一个到服务器的套接字。这浪费了太多的资源。我的问题是如何通过单套接字连接发送/接收数据?
发布于 2013-06-20 00:23:01
通过以下方式使用streams:
AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDel.outputStream write:[data bytes] maxLength:[data length]];
[appDel.inputStream <CALL_YOUR_METHOD>];发布于 2013-06-20 00:22:57
我将创建一个实用程序/管理器类来处理与服务器的通信。这样,您就可以轻松地从代码的其他部分访问它。也很容易确保它是线程安全的。请注意,您应该考虑不在主线程上执行这些操作。
但是,如果您确实想要访问AppDelegate中定义的变量,下面是代码:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.outputStream <method>];https://stackoverflow.com/questions/17195991
复制相似问题