简体   繁体   中英

Python client write to Java's writeUTF method

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() ?

Have a look at the docs for the readUTF function here

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM