【发布时间】:2023-03-18 01:03:01
【问题描述】:
我正在使用 Stream 处理套接字
我使用此代码连接到我的服务器:
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"host", port, &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 *)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);
[self messageReceived:output];
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
theStream = nil;
break;
default:
NSLog(@"Unknown event");
}
}
- (void) messageReceived:(NSString *)message {
}
- (IBAction) sendMessage {
NSString *response = [NSString stringWithFormat:@"msg:%@", inputMessageField.text];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
inputMessageField.text = @"";
}
当我点击按钮发送时显示“未知事件”
【问题讨论】:
-
事件可能是
NSStreamEventHasSpaceAvailable,你确定服务器没有收到你发送的消息吗? -
当我发送消息时,我的服务器收不到我的消息
-
我有一个link 可以帮到你。
-
Int
stream:handleEvent:检查哪些流与每种情况匹配。
标签: ios objective-c sockets nsstream