2015-06-12 70 views
1

我一直在尝试创建一个运行Java中的客户端和Python中的服务器的程序。 我的总体目标是在Java上将客户端上的图片上传到服务器上,并将其存储在mysql服务器上。我还没有尝试过从Python上的图像转换为在mysql上的blob,并已上传到python阶段。这是下面的代码:从java上的客户端发送图像到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

我看不到您在发送图像之前发送图像大小,但在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(); 
} 
+0

首先,感谢您的评论。 然而,它运行这个错误: 类型不匹配:不能从java.io.OutputStream中转换为org.omg.CORBA.portable.OutputStream中 这两种类型似乎不是在第一行某种原因相同。 – Michael

+0

尝试导入java.io.OutputStream而不是org.omg.CORBA.portable.OutputStream – Delimitry

+0

它的工作原理。我爱你。 – Michael

相关问题