gpt4 book ai didi

ios - 无法通过 IOS 套接字发送消息

转载 作者:行者123 更新时间:2023-11-29 13:22:45 24 4
gpt4 key购买 nike

我正在使用 CFStream 构建 IOS 套接字客户端。我已经设法连接到我的测试服务器并从它接收消息。问题是如果客户端发送消息服务器无法接收它,并且之后客户端不会从服务器接收到任何消息。我的代码如下。有什么问题吗?

- (void)initCommunicationWithAddress:(NSString*) address withPort:(int) port
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)address, port, &readStream, &writeStream);

self.inputStream = (__bridge_transfer NSInputStream *)readStream;
self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;

[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
NSLog(@"Socket Init: %@", @"");
}

- (void)sendMessage:(NSString*)msg
{
msg = @"hello";
NSLog(@"SendMessage: %@", msg);
NSData *data = [[NSData alloc] initWithData:[msg dataUsingEncoding:NSASCIIStringEncoding]];
[self.outputStream write:[data bytes] maxLength:[data length]];
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

switch (streamEvent) {

case NSStreamEventOpenCompleted:
[self streamOpened];
break;

case NSStreamEventHasBytesAvailable:
NSLog(@"Stream Bytes Available:%@", @"");
if (theStream == self.inputStream) {

NSMutableData* data = [NSMutableData data];
uint8_t buffer[1024];
int len;
int bytesRead = 0;

while ([self.inputStream hasBytesAvailable])
{
len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {

[data appendBytes:(const void *)buffer length:len];
bytesRead = bytesRead + len;
}
}

NSString* output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

if (nil != output) {
[self HandleServerMessage: output];

}
}
break;

case NSStreamEventErrorOccurred:
NSLog(@"Stream Error:%@", @"");
[self streamError];
break;

case NSStreamEventEndEncountered:
NSLog(@"Stream Event End:%@", @"");
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self streamEnd];
break;

default:
NSLog(@"Unknown event");
}
}

最佳答案

我发现了我的错误。在向服务器发送任何消息之前,我应该等待 NSStreamEventHasSpaceAvailable 事件或检查空间是否可用。

关于ios - 无法通过 IOS 套接字发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13977048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com