Python client write to Java's writeUTF method
Question: I have the following code snippet for a **Java** server that can't be changed:

    
    
     ....
     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)
    

And I have the following client code for **python** :

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

The problem that I'm facing is that I can get the client to send information
to the server but the server won't stop listening, so it stays on the blocking
call `this.dis.readUTF();`.

As you can see I tried using the `\n` character at the end of the string but
it stays listening. Does anybody knows how to write from a python client to a
java server using `readUTF()`?


Answer: Have a look at the docs for the `readUTF` function
[here](https://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#readUTF\(\))

Primarily, this stands out

> 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.

Try something like this in your python code

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

