Python 服务器从 Android 接收图像文件并发送字符串“OK”作为响应。 python服务端源码如下:
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(ADDR)
print('bind')
serverSocket.listen(CLIENT_NUM)
print('listen')
while True:
print('waiting...')
try:
connectionSocket, addr_info = serverSocket.accept()
print('accept')
print('--client information--')
print(connectionSocket)
img = open("./img.jpg", 'wb')
while True:
img_data = connectionSocket.recv(BUFSIZE)
data = img_data
if img_data:
while img_data:
print("receiving Img...")
img_data = connectionSocket.recv(BUFSIZE)
data += img_data
else:
break
img_file = open("img.jpg", "wb")
print("finish img recv")
img_file.write(data)
img_file.close()
connectionSocket.send("OK".encode())
connectionSocket.close()
print('connection closed')
except KeyboardInterrupt:
sys.exit(0)
Android 客户端将图像文件发送到 python 服务器,并从 python 服务器接收字符串“OK”。 python服务端源码如下:
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIp);
socket = new Socket(serverAddr, serverPort);
try {
dataOutput = new DataOutputStream(socket.getOutputStream());
dataInput = new DataInputStream(new FileInputStream(img));
byte[] buf = new byte[BUF_SIZE];
int dataLen;
while ((dataLen = dataInput.read(buf)) != -1) {
dataOutput.write(buf, 0, dataLen);
dataOutput.flush();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Socket", reader.readLine());
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.e("StackTrace", exceptionAsString);
} finally {
try {
if (dataInput != null)
dataInput.close();
if (dataOutput != null)
dataOutput.close();
if (socket != null)
socket.close();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.e("StackTrace", exceptionAsString);
}
}
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.e("StackTrace", exceptionAsString);
}
}
服务器无法
如果我删除下面两行,服务器可以正常接收文件。但是如果我插入下面两行,服务器就不会收到该文件。
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Socket", reader.readLine());
Android客户端如何将图像文件发送到Python服务器并获得响应?
最佳答案
我解决了这个问题。我认为这个问题的原因一定是在服务器端,于是我修改了服务器端的代码,成功了!
img = open("./img.jpg", 'wb')
img_data = connectionSocket.recv(BUFSIZE)
data = img_data
firstPacketLen = len(img_data)
print("receiving Img...")
while len(img_data) > 0:
img_data = connectionSocket.recv(BUFSIZE)
data += img_data
if len(img_data) < firstPacketLen:
break
print("finish img recv")
img.write(data)
img.close()
connectionSocket.send("OK\r\n".encode())
connectionSocket.shutdown(SHUT_RDWR)
connectionSocket.close()
print('connection closed')
关于java - android客户端无法收到python服务器的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54706184/