gpt4 book ai didi

ios - NSOutputStream 打开后不能立即写入?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:34 25 4
gpt4 key购买 nike

我正在学习iOS网络编程来自this教程。我尝试修改代码,以便在连接成功后立即向服务器发送响应。我更改的代码的唯一部分是在此函数中。问题是应用程序停止并且在 [outputStream write:[data bytes] maxLength:[data length]]; 行没有任何反应因此 NSLog(@"sent test"); 没有被执行。我做错了什么?

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {       
NSLog(@"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");

//my code
if (theStream == outputStream) {
NSLog(@"outputStream");
NSData* data = [NSData dataWithBytes:@"test" length:4];
[outputStream write:[data bytes] maxLength:[data length]];
NSLog(@"sent test");
} //end my code

break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
//...
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[theStream release];
theStream = nil;
break;
default:
NSLog(@"Unknown event");
}
}

编辑:在这里找到解决方案 How to use NSOutputStream's write message?

最佳答案

好的,当我使用原始套接字连接时,我已经使用该代码将数据发送到服务器。可能对你有帮助

if (theStream == outputStream) {
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];//str is my string to send
int byteIndex = 0;
uint8_t *readBytes = (uint8_t *)[data bytes];
readBytes += byteIndex; // instance variable to move pointer
int data_len = [data length];
// NSLog(@"%i",[data length]);
unsigned int len = ((data_len - byteIndex >= 1024) ?
1024 : (data_len-byteIndex));
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);
len = [outputStream write:(const uint8_t *)buf maxLength:len];
byteIndex += len;

}

关于ios - NSOutputStream 打开后不能立即写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15491499/

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