简体   繁体   English

从java客户端发送图像到python服务器

[英]Send an image from java client to python server

I am trying to send an image in the form of a byte array from a client application to a server.我正在尝试以字节数组的形式将图像从客户端应用程序发送到服务器。 The server code is written in python while the client is written in java.服务器代码是用python编写的,而客户端是用java编写的。 The image is being transferred correctly however the image saved on the server machine is corrupted.图像正在正确传输,但保存在服务器计算机上的图像已损坏。

The following is the code for the server.以下是服务器的代码。

import socket
import struct

HOST = "192.168.1.100"
PORT = 9999

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)

print('SERVER STARTED RUNNING')

while True:
    client, address = s.accept()
    buf = ''
    while len(buf) < 4:
        buf += client.recv(4 - len(buf))
    size = struct.unpack('!i', buf)[0]
    with open('/home/isaac/Desktop/image.jpg', 'wb') as f:
        while size > 0:
            data = client.recv(1024)
            f.write(data)
            size -= len(data)
    print('Image Saved')
    client.sendall('Image Received')
    client.close()

The following is the source code for the java client:下面是java客户端的源码:

public static void main(String[] args) throws IOException {
    byte[] array = extractBytes("/home/isaac/Desktop/cat.jpg");
    Socket sock = new Socket(IP_ADDRESS, PORT_NO);
    DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
    System.out.println("Array Length - " + array.length);
    dos.writeInt(array.length);
    dos.write(array);
    BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    System.out.println(reader.readLine());
}

Hopefully you can help me.希望你能帮助我。 I've tried to google to get my answer but no solution has worked so far.我试图谷歌得到我的答案,但到目前为止没有任何解决方案。

In what sense you get a corrupted image?在什么意义上你会得到一个损坏的图像? I've tried it with the following array:我已经用以下数组尝试过它:

byte[] array = new byte[3000];
for(int i=0; i<array.length; i++) {
    array[i] = (byte)('0' + (i % 10));
}

and I get the same array I sent.我得到了我发送的相同数组。

Another thing, just to be sure: the file is less than 2Gb, right?另一件事,请确定:文件小于 2Gb,对吗?

This can help you这可以帮助你

import java.nio.file.Files;
File file = new File("picture path");
byte[] array = Files.readAllBytes(file.toPath());

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

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