Python套接字服务器接收图像 [英] Python socket server receive image

查看:160
本文介绍了Python套接字服务器接收图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to receive an image from Android to PC using socket in Python. My server code is as follows:

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大小相同.但是我无法打开图片.

And it returns me a tst.jpg which is the same size of that on my Android. But I cannot open the pic.

这是我的Android代码:

Here is my Android code:

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();

推荐答案

,因此android代码将数据大小作为int形式发送到数据的前面,但是python代码无法读取它.

so the android code is sending the size as int in front of the data, but the python code doesn't read it.

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()

这篇关于Python套接字服务器接收图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆