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服务器发送一个图像文件并得到响应?你知道吗
我解决了这个问题。我想这个问题的原因一定是在服务器端,所以我修改了服务器的代码,它工作了!你知道吗
相关问题 更多 >
编程相关推荐