简体   繁体   中英

Android Socket InputStream problem

I have a server written in VB, it sends data to clients in periods of 3 seconds. I've written a client Java code like this:

class Commu extends Thread {
   Socket socket;
   InputStream inputStream;
   OutputStream outputStream;

   public Commu() {
      try {
         socket=new Socket();
         socket.connect(new InetSocketAddress("192.168.0.1", 1234)));

         inputStream=socket.getInputStream();
         outputStream=socket.getOutputStream();
         this.start();
      } catch(Exception e) {
         System.out.println(e);
      }
   }

   public void run() {
      while(true) {
         byte[] buffer=new byte[1024];
         inputStream.read(buffer);
         System.out.println(buffer[0]);
      }
   }
}

It works fine on my desktop, it prints message whenever the VB server sends message.

It works on Android, but the inputStream read only once, and then get stuck; If I want to read more data, I have to use outputStream to send some data, then inputStream will read once, and get stuck again. That is really strange, could anyone tell me why?

There is no problem in System.out.print() , because DDMS can show it, I promise! The problem is inputStream should not read only once, it should read when data comes. But it didn't, it read only once.

Even if, I only print one byte from the buffer, it get stuck on Android. It works very well on desktop, but get stuck on Android.

That's a wierd piece of code. You don't check the return value of read() for -1, ie EOS, and you only display the first byte of the data received and throw the rest away.

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