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

IOS套接字写入服务器,服务器从客户端接收数据,ios,sockets,Ios,Sockets,Im使用此代码将图像数据发送到服务器 - (void)sendImageData: (UIImage *)image { NSData *imageData = [UIImagePNGRepresentation(image) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength]; [outputStream write:[imageData bytes] maxLength:[imageData leng

Im使用此代码将图像数据发送到服务器

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

问题是:当我选择一个小尺寸的图像时,服务器将完全接收我发送的图像数据。然而,当我发送一个较大的映像时,服务器将不会接收我的所有数据。 为什么?帮助我? 服务器接收数据代码:

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];

我假设您正在使用TCP,并且处于块模式。TCP不会一次发送所有数据,所以应该在while循环中调用read方法。当tcp的接收缓冲区中有1个字节时,read方法返回。默认情况下,您必须关闭客户端连接以告知服务器您已完成传输,否则服务器将永远不会离开while循环

我没有测试代码,你可以试一下,如果不起作用,告诉我

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 ;
    }
}

你好,库多克,谢谢你的回复!我已经测试了您的代码:我通过以下方式将imageDataLeng发送到服务器:int32_t dataLength=[imageData length];[outputStream写入:uint8_t*&数据长度最大长度:4];然后我接收:dataleng知道lengOfDataReceive,然后循环stringData.length