Python套接字服务器接收图像

时间:2014-04-26 14:46:51

标签: python image sockets

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

import socket
address = ("10.0.0.12", 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(1000)


client, addr = s.accept()
print 'got connected from', addr

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

client.close()

它返回给我一个tst.jpg,与我在Android上的大小相同。但我无法打开图片。

这是我的Android代码:

Socket photoSocket = new Socket(ipString, port);
DataOutputStream dos = new DataOutputStream(photoSocket.getOutputStream());
FileInputStream fis = new FileInputStream(PhotoActivity.filePath);
int size = fis.available();

byte[] data = new byte[size];
fis.read(data);
dos.writeInt(size);
dos.write(data);

dos.flush();
dos.close();
fis.close();
photoSocket.close();

1 个答案:

答案 0 :(得分:2)

所以android代码在数据前发送大小为int,但是python代码没有读取它。

import socket
import struct
address = ("10.0.0.12", 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(1000)


client, addr = s.accept()
print 'got connected from', addr

buf = ''
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)
        if not data:
            break
        img.write(data)
print 'received, yay!'

client.close()