我正在尝试以字节数组的形式将图像从客户端应用程序发送到服务器。服务器代码是用python编写的,而客户端是用java编写的。正确传输图像,但保存在服务器计算机上的图像已损坏。
以下是服务器的代码。
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()
以下是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());
}
希望你能帮助我。我试图谷歌得到我的答案,但到目前为止还没有解决方案。
答案 0 :(得分:0)
在什么意义上你会得到一个损坏的图像?我用以下数组尝试过它:
byte[] array = new byte[3000];
for(int i=0; i<array.length; i++) {
array[i] = (byte)('0' + (i % 10));
}
我得到了我发送的相同数组。
另一件事,只是为了确定:文件小于2Gb,对吧?
答案 1 :(得分:0)
这可以帮助您
import java.nio.file.Files;
File file = new File("picture path");
byte[] array = Files.readAllBytes(file.toPath());