如果您需要进一步的解释或详细信息,我会尽我所能解释,请发表评论..
我在我的计算机上运行了一个本地 python 服务器,它根据请求向客户端提供消息。
我有一个 MAC 客户端应用程序,其中有 3 个类 -
Chatlogic 类——该类初始化连接并发送和接收来自服务器的消息。
登录类 - 这维护用户对应用程序的登录,在这个类中我有一个 Chatlogic 类的实例,我可以通过这样的 chatlogic 类的对象发送消息 [chatLogicObject sendmessage: something ]
我的问题是这个=当我收到它时,它来自 chatLogic 类实例而不是 LoginClass 所以我在登录类中有一个名为 -(void)messageReceived 的方法,它应该覆盖 chatLogic 类中的相同方法(但这不会工作)。我如何在 Loginclass 中接收方法?
为了避免混淆,我添加了我的聊天逻辑类
#import <Foundation/Foundation.h>
@interface chatLogic : NSObject <NSStreamDelegate>
@property (copy)NSOutputStream *outputStream;
@property (copy)NSInputStream *inputStream;
@property (copy)NSString *streamStatus;
-(void)initNetworkCommunications;
-(void)sendMessage:(id)sender;
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent;
-(void)messageReceived:(NSString*)message; //i want this method to be used in some other classes
@end
实现文件如下
导入“chatLogic.h”
@实现聊天逻辑
@synthesize 输入流;@synthesize 输出流;@synthesize 流状态;
-(id)初始化{
if (self == [super init]) {
}
return self;
}
-(void)initNetworkCommunications{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.22", 80, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent{
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
streamStatus = [[NSString alloc]initWithFormat:@"Stream opened"];
break;
case NSStreamEventHasBytesAvailable:
if (aStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = (int)[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);
[self messageReceived:output];
}
}
}
}
case NSStreamEventErrorOccurred:
{
NSLog(@"cannot connect to the host!");
break;
}
case NSStreamEventEndEncountered:
{
break;
}
default:
{
NSLog(@"unknown event!!");
}
}
}
-(void)sendMessage:(id)sender{
}
-(void)messageReceived:(NSString*)message{
NSLog(@"the received message in chat logic class");
}
-(无效)dealloc{
[inputStream close];
[outputStream close];
[inputStream release];
[outputStream release];
[super dealloc];
}
@结尾