我现在要吃我的键盘了。 我写了一个程序来发送和接收来自服务器的消息。发送消息没有问题。但是当我尝试使用textView显示所有消息时,只有我发送的消息显示出来。
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
NSLog(@"stream event %i", eventCode);
switch (eventCode) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (aStream == inPutStream) {
uint8_t buffer[1024];
int len;
while ([inPutStream hasBytesAvailable]) {
len = [inPutStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
Message = [[NSString alloc] initWithBytes:buffer
length:len encoding:NSASCIIStringEncoding];
[self recvMessage:Message];
}
}
}
break;
default:
;
}
}
- (void)recvMessage:(NSString *)output{
self.textView.text = [NSString stringWithFormat:@"%@\n%@",self.textView.text,output];
}
这是标题
@interface ViewController : UIViewController <NSStreamDelegate>
- (IBAction)backGround2:(id)sender;
- (IBAction)backGround:(id)sender;
@property (retain, nonatomic) IBOutlet UITextView *textView;
@property (retain, nonatomic) IBOutlet UITextField *textFeild;
- (IBAction)sendBotton:(id)sender;
@property (retain, nonatomic) IBOutlet UITextField *hostName;
@property (retain, nonatomic) IBOutlet UIView *MainView;
@property (retain, nonatomic) IBOutlet UIView *chatView;
- (IBAction)connectBotton:(id)sender;
- (IBAction)disConnect:(id)sender;
@end
NSString *Message;
NSInputStream *inPutStream;
NSOutputStream *outPutStream;
除了显示来自服务器的消息外,一切正常。但是当我改变时:
[self.recvMessage:Message` to `NSLog(@"%@",Message)
我可以在目标输出中看到该消息。
在服务器上运行的客户端肯定发送了消息。
答案 0 :(得分:0)
尝试
- (void)recvMessage:(NSString *)output
{
if ([txtvw.text length] > 0)
{
txtvw.text = [NSString stringWithFormat:@"%@\n%@", txtvw.text, output];
}
else
{
txtvw.text = [NSString stringWithFormat:@"%@", output];
}
}
答案 1 :(得分:0)
听起来像是一个线程问题,网络发生在后台线程上,因此你没有在UI(即主要)线程上进行更新。
你可以尝试这个来快速修复。替换:
[self recvMessage:Message];
与
[self performSelectorOnMainThread:@selector(recvMessage:) withObject:Message waitUntilDone:NO];
或等效的gcd变体。