到目前为止,我可以连接,发送一条消息,在服务器端收到,但随后我的应用程序崩溃.
ClIEnt.h
#import <Foundation/Foundation.h>@interface ClIEnt : NSObject <NsstreamDelegate>{ NSinputStream *inputStream; NSOutputStream *outputStream;}-(voID)initNetworkCommunication;-(voID)send:(Nsstring*)message;@end
ClIEnt.m
#import "ClIEnt.h"@implementation ClIEnt- (voID)initNetworkCommunication { CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(NulL,(CFStringRef)@"10.0.1.51",7769,&readStream,&writeStream); inputStream = ( NSinputStream *)CFBrIDgingrelease(readStream); outputStream = ( NSOutputStream *)CFBrIDgingrelease(writeStream); [inputStream setDelegate:self]; [outputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; [outputStream open];}- (voID)send:(Nsstring*)message{ NSData *data = [[NSData alloc] initWithData:[message dataUsingEnCoding:NSUTF8StringEnCoding]]; [outputStream write:[data bytes] maxLength:[data length]];}- (voID)stream:(Nsstream *)theStream handleEvent:(NsstreamEvent)streamEvent { NSLog(@"stream event %i",streamEvent); switch (streamEvent) { case NsstreamEventopenCompleted: NSLog(@"Stream opened"); break; case NsstreamEventHasBytesAvailable: 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); } } } } break; case NsstreamEventErrorOccurred: NSLog(@"Can not connect to the host!"); break; case NsstreamEventEndEncountered: NSLog(@"End Encountered!"); [theStream close]; [theStream removeFromrunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; theStream = nil; break; default: NSLog(@"UnkNown event"); }}@end
控制台中的输出是
2013-10-03 17:01:38.542 MMORPG[6076:70b] stream event 12013-10-03 17:01:38.543 MMORPG[6076:70b] Stream opened2013-10-03 17:01:43.495 MMORPG[6076:70b] stream event 42013-10-03 17:01:43.495 MMORPG[6076:70b] UnkNown event
好像,我的消息被发送,我接收流事件#4,然后我得到一个糟糕的访问崩溃.问题是我不知道它访问有什么问题?
任何帮助将不胜感激!
@R_502_6120@ 问题是Nsstream保持对其委托的assign / unsafe_unretained引用.如果在关闭和释放流之前释放了委托,则流将尝试在其现在取消分配的委托上调用方法,从而导致崩溃.解决方案是确保某个其他对象具有对客户端的强引用,防止其早期解除分配,或者确保在其委托被取消分配之前关闭并释放该流. 总结以上是内存溢出为你收集整理的写入后NSOutputStream与Bad Access崩溃(Objective-c)全部内容,希望文章能够帮你解决写入后NSOutputStream与Bad Access崩溃(Objective-c)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)