Python 客户端写入 Java 的 writeUTF 方法

Python client write to Java's writeUTF method

我有以下无法更改的 Java 服务器的代码片段:

 ....
 while(true){
 try {
            System.out.println("Will listen . . .");
            instruction = this.dis.readUTF();  // Socket's dataInputStream
            System.out.println("Got instruction: " + instruction);
        } catch (IOException ex) {
            Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
        }

  ....
 } // end while(true)

我有以下 python 的客户端代码:

.... 
self.socket.send(b"GET~CARD\n")
print self.socket.recv(1024)
....

我面临的问题是,我可以让客户端向服务器发送信息,但服务器不会停止监听,所以它一直处于阻塞状态 this.dis.readUTF();

如您所见,我尝试在字符串末尾使用 \n 字符,但它仍然在监听。有人知道如何使用 readUTF() 从 python 客户端写入 java 服务器吗?

查看 readUTF 函数的文档 here

首先,这很突出

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.

在您的 python 代码中尝试这样的事情

import struct
message = u"GET~CARD\n"
size = len(message)
...
sock.send(struct.pack("!H", size))
sock.send(message)