python3.4套接字服务器接收图像

时间:2015-11-03 10:00:37

标签: android image sockets python-3.4

我正在尝试使用Python 3.4中的套接字从Android到PC接收图像。我的服务器代码如下:

import socket
import struct
import sys
address = ("10.0.0.22", 5000)
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except (socket.error, msg):
    print ('Failed to create socket.Error code:' + str(msg[0]) + ', Error    message: ' + msg[1])
sys.exit()
print ('Socket Created')
s.bind(address)
s.listen(5)

while True:
    (client, addr) = s.accept()
    print ('got connected from', client,addr)
    buf = b''
    while len(buf)<4:
        buf += client.recv(4-len(buf))
    size = struct.unpack('!i', buf)
    print ("receiving %s bytes" % size)

    with open('tst.jpg', 'wb') as img:
        while True:
            data = client.recv(1024)
            print (data)
            if not data:
                break
            img.write(data)
    img.close()
print ('received, yay!')
client.close()

但它返回给我一个tst.jpg比我的Android图像少4个字节。我无法打开图像。

这是我的Android代码:

FileOutputStream fop;
Socket socket;
try {
    fop=new FileOutputStream("/sdcard/dd.jpg");
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, fop);
    fop.close();
    Toast.makeText(MainActivity.this, "saved",Toast.LENGTH_LONG).show();

    InetAddress serverAdd = InetAddress.getByName("10.0.0.22");
    SocketAddress sc_add = new InetSocketAddress(serverAdd,5000);
    socket = new Socket();
    socket.connect(sc_add,2000);

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] bytes = baos.toByteArray();
    out.write(bytes);
    out.close();
    socket.close();
}

1 个答案:

答案 0 :(得分:0)

python服务器需要前四个字节,表示后面文件的长度。

您的Android代码不会发送包含字节数组长度的整数的四个字节。

因此首先发送这样一个整数的四个字节。

 int size = bytes.length;