gpt4 book ai didi

objective-c - 何时关闭 NSOutputStream?

转载 作者:行者123 更新时间:2023-12-03 16:27:59 26 4
gpt4 key购买 nike

我想通过套接字将 UIImage 的数据发送到服务器,所以我:

a) 打开 NSOutputStream


- (IBAction)send:(id)sender {
NSURL *website = [NSURL URLWithString:str_IP];
NSHost *host = [NSHost hostWithName:[website host]];
[NSStream getStreamsToHost:host port:1100 inputStream:nil outputStream:&oStream];
[oStream retain];
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];
}

b) 当空间可用时将数据写入oStream


- (void) stream: (NSStream *) stream handleEvent: (NSStreamEvent) eventCode
{
switch(eventCode)
{
case NSStreamEventHasSpaceAvailable:
{
if(stream == oStream)
{
NSData *data = UIImageJPEGRepresentation(drawImage.image, 90);
//Convert from host to network endianness
uint32_t length = (uint32_t)htonl([data length]);

[oStream write:(uint8_t *)&length maxLength:4];
[oStream write:[data bytes] maxLength:length];
}
}
break;
}

问题是数据不断地写入oSream。数据全部发送完后如何停止?

我在图像数据之前发送数据的长度,以便让服务器知道它何时到达末尾。我是否必须更改服务器端的代码才能在套接字到达末尾时关闭套接字?在哪里可以添加[oStream close]来关闭客户端的oStream?

最佳答案

The problem is that the data keeps writing to the oSream again and again. How to stop it when all the data is sent?

看,这就是用被动语态思考的危险。用主动语态重新表述问题:

The problem is that the data keeps writing to the oSream again and again. How to stop it when I have sent all the data?

你几乎已经回答了你自己的问题。

问题的很大一部分是您的 HasSpaceAvailable 处理程序。这就是你正在做的事情:

  1. 创建图像的完整 JPEG 表示形式(每次)
  2. 发送表示的长度(每次)
  3. 发送表示的第一部分(每次)

这是三个问题,您需要解决这三个问题。

  1. 创建 JPEG 表示一次。
  2. 仅发送一次表示形式的长度。
  3. 跟踪您已发送的内容,并仅发送未发送内容的第一部分。

要完成这三个操作,请将长度放入 NSMutableData 并将 JPEG 表示形式附加到其中。然后,保留这个新的数据对象,并为字节指针和剩余长度添加额外的实例变量。您将在进入 HasSpaceAvailable 状态之前完成所有这些操作。

然后,当您到达 HasSpaceAvailable 时,不要单独发送长度,因为您已将其放入数据对象中。您只需发送指针实例变量中的字节,并将剩余长度作为最大长度。检查发送的字节数不是 0 或 -1 后(请参阅 the documentation ),将其添加到指针并从剩余长度中减去它。

当剩余长度为零时,您已发送所有内容。假设您不想在 JPEG 数据之后添加某些内容,则可以关闭该流。

关于objective-c - 何时关闭 NSOutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/712810/

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