我一直在尝试创建一个用Java运行客户端而用Python运行服务器的程序。 我的总体目标是将来自Java客户端的图片上传到Python上的服务器并将其存储在mysql服务器上。我还没有尝试过将Python上的图像转换为mysql上的blob已经陷入上传到python阶段。这是以下代码:
客户:( java)
client.send("upload##user##pass##"); //this is how i know that upload request has been sent.
String directory = "/home/michael/Pictures/"+field.getText();// a valid directory of a picture.
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(new File(directory));
} catch (IOException err) {
err.printStackTrace();
}
try {
ImageIO.write(bufferedImage, "png", client.socket.getOutputStream());//sending the picture via socket.
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
这是服务器:( Python)
elif mar[0]=="upload":##this is how i know that the request is to upload
buf = ''
while len(buf)<4:
buf += clientsock.recv(4-len(buf))
size = struct.unpack('!i', buf)
print "receiving %s bytes" % size
with open('tst.jpg', 'wb') as img:
while True:
data = clientsock.recv(1024)
if not data:
break
img.write(data)
print 'received, yay!'
这段代码实际上不起作用并打印出我要发送的大量字节(图片大约2 gb)我没有和服务器/客户端一起工作很多,所以这段代码可能很糟糕。
答案 0 :(得分:0)
我无法看到您在发送图像之前发送图像大小,但在Python代码中,您首先要读取4个字节的图像大小。
您需要在Java代码中添加图像大小的发送:
try {
OutputStream outputStream = client.socket.getOutputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
// get the size of image
byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
outputStream.write(size);
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}