How to use NSOutputStream's write message?

后端 未结 1 1417
有刺的猬
有刺的猬 2020-12-08 06:18

I want to send a UIImage to a server through a socket.

a)I open the outputstream:


- (IBAction)send:(id)sender {
    NSURL *website = [NSURL URLWithS         


        
相关标签:
1条回答
  • 2020-12-08 06:26

    You should be writing the data only after space becomes available in the output stream. When the stream finishes opening, it doesn't always immediately have space available, so writing to it won't work. If you move the write call to the NSStreamEventHasSpaceAvailable handler, it should succeed.

    Also, the computer on the other end of the socket has no way of knowing the length of the data you're sending. Unless you're signaling the end-of-data by closing the socket, you should explicitly send the data length along with the data:

    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]);
            // Don't forget to check the return value of 'write'
            [oStream write:(uint8_t *)&length maxLength:4];
            [oStream write:[data bytes] maxLength:length];
        }
        break;
    }
    
    0 讨论(0)
提交回复
热议问题