通过wifi将NSData发送到Java Server

时间:2014-02-26 17:26:39

标签: java ios iphone objective-c java-server

我试图通过wifi&发送NSString它没有错误地工作。对于NSString,我在iOS应用程序中都使用了NSUTF8StringEncoding。 Java服务器端。

现在我想通过wifi将NSData(图像)发送到我的java服务器。我将使用此代码将图像发送到java服务器。

NSData *newData = UIImagePNGRepresentation([UIImage imageNamed:@"Default.png"]);
    int index = 0;
    int totalLen = [newData length];
    uint8_t buffer[1024];
    uint8_t *readBytes = (uint8_t *)[newData bytes];

    while (index < totalLen) {
        if ([outputStream hasSpaceAvailable]) {
            int indexLen =  (1024>(totalLen-index))?(totalLen-index):1024;

            (void)memcpy(buffer, readBytes, indexLen);

            int written = [outputStream write:buffer maxLength:indexLen];

            if (written < 0) {
                break;
            }

            index += written;

            readBytes += written;
        }
    }

我的问题是,我可以在java服务器中读取NSData吗?如果我不能解决什么问题?我应该使用编码方法吗? 还有人可以给我一个示例Java服务器代码来以某种方式读取NSData或图像....

1 个答案:

答案 0 :(得分:3)

private void saveFile(Socket socket, File receivingFile) {
        try {
            FileOutputStream wr = new FileOutputStream(receivingFile);
            byte[] buffer = new byte[socket.getReceiveBufferSize()];
            int bytesReceived = 0;

            while ((bytesReceived = socket.getInputStream().read(buffer)) > 0) {
                wr.write(buffer, 0, bytesReceived);
            }
            wr.close();
            setLogMessege("SaveFile", "File Written");
            socket.close();
        } catch (IOException e) {
            try {
                socket.close();
            } catch (IOException ex) {
                Logger.getLogger(AcceptCameraImages.class.getName()).log(Level.SEVERE, null, ex);
            }
            setLogMessege("SaveFile", e.getMessage());
        }`enter code here`