java - 从客户端(Android-Mobile)向服务器(Python)发送消息
问题描述
我正在开发一个具有服务器(Python 3.x)和客户端(Android Studio)的项目。客户端(手机)获取图像(位图)并将其发送到服务器(Python)。在服务器部分,它会做一些深度学习的工作并生成预测。因此,我需要将该预测(字符串)发送回客户端。但是,我正在使用套接字编程并且它不起作用。我已经为此工作了很长时间,并且截止日期即将到来。那么,有人可以帮助我吗?
错误可能是 clientSocket.getInputStream() 的原因(但我不确定)
这是服务器(PYTHON)的样子
import socket
import base64
HOST = 'localhost'
PORT = 5433 # 1023 ten büyük bir sayı olsun.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(5)
i = 1 #Dosya adıyla ilgili.
while True:
conn, addr = s.accept()
with conn:
print(' > connected by ', addr)
#Take image that was sent from Client
data = base64.b64encode(b'')
while True:
yenidata = conn.recv(1024)
if not yenidata:
break
data = data + yenidata
#Save the image to do DL part.
fileName = 'yeniResim'+str(i)
with open("C:/Users/MUSTAFAAKTAS/Desktop/Indirilenler/"+fileName+".png", "wb") as fh:
fh.write((base64.decodebytes(data)))
i = i + 1
print(" >",fileName," saved.")
#In here, I randomly wrote "Message", but in real, I do some DL stuff and try to send the prediction to the Client
conn.send(bytes("Message",'UTF-8'))
print(" > Message sent")
现在客户(ANDROID)在这里,
#I create a connection like this,
Socket client = new Socket(IP, PORT);
#I need 'cevap' which is the prediction that was sent from the server to client
String cevap = ServerRespond();
public String ServerRespond(){
if(client.isClosed()) {
return "SERVER Closed";
}
else {
try {
ServerSocket ss = new ServerSocket(5433);
Socket s = ss.accept();
InputStream sin = s.getInputStream();
DataInputStream dis = new DataInputStream(sin);
return dis.readUTF().toString();
} catch (SocketTimeoutException s) {
return "Socket timed out!";
} catch (Exception ioe) {
return "IO HATASI " + ioe.getLocalizedMessage();
}
}
}
太感谢了。
解决方案
推荐阅读
- qt - 如何使用 QMessageBox 显示纯文本?
- python - 遍历进程列表以检查 PID 是否与 Python 子进程一起存在
- c++ - 正则表达式在 23 个字符处停止工作,但前提是我传入字符串文字
- windows - 在两个不同进程之间共享文件句柄
- arrays - 在多个文本文件中搜索字符串并通过将其附加到 summary_[date].log 来复制行
- asp.net - IIS 上的 ASp.Net MVC 站点,仅 CSS 文件出现 500 错误
- java - 当我尝试调试单个单元测试时,IntelliJ IDEA 运行完整的测试套件
- javascript - SharePoint JavaScript 更新选项 field.set_choice 不存在
- javascript - 通过 https net::ERR_CONNECTION_CLOSED 将 SOCKET.IO-client (angular) 连接到 SOCKET.IO-server (node.js)
- wordpress - 为什么谷歌说我的网站有“noindex”?