简体   繁体   中英

Sending data using a python client to a java server

I have been searching the web for a while now looking for an answer to this.

The python code for sending a file:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with open(path, mode='rb') as f:
   s.sendall(f.read())

The java code for receiving the data:

 private BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))) {
      while (true) {
          int size = bis.read(by);
          if (size > 0) {
              bos.write(by, 0, size);
              bos.flush();
              total += size;
              System.out.println(size + "(" + total + ")");
              if (total == length) {
                  break;
              }
           }
        }
   }.....

I see that the data is being sent, and i know the data is in the stream at the java end. However the bis.read(by) call hangs, and refuses to read the data until the data the connection dies.

I suspect it has something to do with the "flush" stuff in java, but i can not find any way to do a "flush" using python.

Any clues why this might happen?

I figured it out, for some reason a race condition is occuring, putting a sleep(0,2) in the python code made the java server able to responde.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sleep(0.2)
with open(path, mode='rb') as f:
   s.sendall(f.read())

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