我正在尝试在 Python 服务器(理想情况下,具有通过 GPIO 连接的某些设备的 Raspberry Pi)和 Java 客户端(同样,主要目标是 Android 应用程序)之间交换一些字符串数据。无论如何,下面的代码是在标准的本地 PC 上运行的。这是服务器的代码,取自(并稍作修改)here:import socketserverimport datetimeclass MyTCPHandler(socketserver.StreamRequestHandler): def handle(self): now = datetime.datetime.now() answer = now self.data = self.rfile.readline().strip() print("Read!") if str(self.data) == 'date': answer = now.date() elif str(self.data) == 'time': answer = now.time() self.wfile.write((str(answer)+"\n").encode('utf-8')) print("Sent!")if __name__ == "__main__": HOST, PORT = "localhost", 9999 with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server: print("Server is running on {}, port {}".format(HOST, PORT)) server.serve_forever()Java客户端如下:public class SocketTest { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1", 9999); PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); out.println("date".getBytes()); String resp = in.readLine(); System.out.println("Received: " + resp); } catch (IOException ex) { Logger.getLogger(SocketTest.class.getName()).log(Level.SEVERE, null, ex); } } }没有抛出任何异常,它只是在客户端等待响应时卡住了,我永远看不到"Read!"服务器端的消息。来自网络上的"date".getBytes()某个地方,我发现 Python 套接字需要字节(UTF-8),但在 Java 中我直接发送字符串,所以它可能是错误的。任何帮助将不胜感激!
添加回答
举报
0/150
提交
取消