简体   繁体   English

iOS套接字写入服务器,服务器从客户端接收数据

[英]IOS Socket write to server and server receive data from client

Im using this code to send image data (nsdata)to server 我正在使用此代码将图像数据(nsdata)发送到服务器

- (void)sendImageData: (UIImage *)image {
NSData *imageData = [UIImagePNGRepresentation(image) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
[outputStream write:[imageData bytes] maxLength:[imageData length]];

} }

problem is: when I select a small size image, server will receive completely image's data Ive sent. 问题是:当我选择较小尺寸的图像时,服务器将完全接收Ive发送的图像数据。 However, when I send a lager image, server will not receive all my data. 但是,当我发送更大的图像时,服务器将不会收到我的所有数据。 Why? 为什么? Help me? 帮我? Server receive data code: 服务器接收数据代码:

int n = read(newSocket, buffer, 1024*256);
if (n < 0) {
    NSLog(@"error reading from socket!");
    return;
}
NSString *buffer2string = [NSString stringWithFormat:@"%s",buffer];
[stringData appendString:buffer2string];

I assume you are using TCP and in a block mode. 我假设您正在使用TCP并处于阻止模式。 TCP won't send all the data in one time, so you should call read method in a while loop. TCP不会一次发送所有数据,因此您应该在while循环中调用read方法。 (read method returns when there are 1 byte in tcp's receive buffer by default) You must close the client connection to tell the server you have finished transmitting, or the server will never leave the while loop. (默认情况下,当tcp的接收缓冲区中有1个字节时,read方法将返回)。您必须关闭客户端连接以告知服务器您已完成传输,否则服务器将永远不会退出while循环。

I didn't test the code, you can try it and tell me if it doesn't work. 我没有测试代码,您可以尝试一下并告诉我它是否无效。

int position = 0 ;
while (1) {
    int n = read(newSocket, buffer+position, 1024*256-position);
    if (n < 0) {
        NSLog(@"error reading from socket!");
        break ;
    } else if (n == 0) {
        NSLog(@"socket closed by peer") ;
        break ;
    } else {
        position += n ;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM