简体   繁体   English

Android Socket InputStream问题

[英]Android Socket InputStream problem

I have a server written in VB, it sends data to clients in periods of 3 seconds.我有一个用 VB 编写的服务器,它以 3 秒的时间向客户端发送数据。 I've written a client Java code like this:我编写了一个客户端 Java 代码,如下所示:

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.它在我的桌面上运行良好,每当 VB 服务器发送消息时它都会打印消息。

It works on Android, but the inputStream read only once, and then get stuck;它适用于Android,但inputStream只读一次,然后卡住; 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.如果我想读取更多的数据,我必须使用outputStream发送一些数据,然后inputStream将读取一次,并再次卡住。 That is really strange, could anyone tell me why?真的很奇怪,谁能告诉我为什么?

There is no problem in System.out.print() , because DDMS can show it, I promise! System.out.print()没有问题,因为 DDMS 可以显示,我保证! The problem is inputStream should not read only once, it should read when data comes.问题是inputStream不应该只读取一次,它应该在数据到来时读取。 But it didn't, it read only once.但它没有,它只读了一次。

Even if, I only print one byte from the buffer, it get stuck on Android.即使我只从缓冲区打印一个字节,它也会卡在 Android 上。 It works very well on desktop, but get stuck on Android.它在台式机上运行良好,但卡在 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.您不检查 read() 的返回值是否为 -1,即 EOS,并且您只显示接收到的数据的第一个字节并将 rest 扔掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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