Android wifi:处理程序消息无法正常工作

时间:2017-07-19 16:54:36

标签: android tcp client wifi handler

我想在Wifi客户端通信中询问有关我的代码的问题。我正在与Raspberry Pi作为服务器进行通信。 我的代码的架构是:

  • 主要活动:我有Handler类,我在OnCreat中启动了第一个负责建立wifi连接的Thread(Thread1)。

    public class MainActivity extends AppCompatActivity {
    public int serverPort = 40000;
    public String serverIP = "10.177.86.212";
    public WiFiConnector wifiConnection;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    editTextWE = (EditText) findViewById(R.id.editText_WE);
    
    wifiConnection = new WiFiConnector(serverIP, serverPort);
    
    Handler mHandler = new MyHandler();
    
    WiFiConnector.Thread1 = new Thread(new WiFiConnector.Thread1(mHandler,true));
    WiFiConnector.Thread1.start();
    }
    
    private class MyHandler extends Handler {
    private byte[] bytes = null;
    
    @Override
    public void handleMessage(Message msg) {
          bytes = msg.getData().getByteArray("KEY");
          if(bytes!= null){
            for (int i = 0; i < bytes.length; i++){
                Log.d("Data received", "value " + (0xFF & bytes[i]) );
            }
    
            for (int i=0; i<bytes.length; i++) {
                editTextWE.setText(editTextWE.getText()+ "Server says: " + bytes.length + " "+ (0xFF & bytes[i]) + "\n");
            }
        }
    }
    }
    }
    
    • WifiConnector类:Thread1和Thread2共享来自Main Activity的处理程序。 Thread1向Raspberry Pi发送命令让它开始发送数据。 Thread2专用于读取从服务器接收的数据。

      public class WiFiConnector {
      
      static String serverIP;
      static int serverPort;
      public static Thread Thread1 = null;
      
      //Constructor
      public WiFiConnector(String IP, int port) {
      serverIP = IP;
      serverPort = port;
      }
      
      public static class Thread1 extends Thread implements Runnable {
      
      private Handler handler1;
      boolean firsttime = false;
      OutputStream out ;
      
      public Thread1(Handler handler_1, boolean firsttime) {
      this.handler1 = handler_1;
       this.firsttime = firsttime;
      }
      
      public void run() {
      Socket socket = null;
      
      try {
      
          //Writing to a Socket
          InetAddress serverAddress = InetAddress.getByName(serverIP);
          socket = new Socket(serverAddress, serverPort);
      
          out = new DataOutputStream(socket.getOutputStream());
          if(firsttime){
          //I send "B" to Raspberry to let him start sending data
          out.write("B".getBytes());
          this.fisrttime = false;
          }
      
          Thread2 comThread = new Thread2(socket, handler1);
          new Thread(comThread).start();
      
      } catch (UnknownHostException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      }
      }
      
      public static class Thread2 implements Runnable {
      
      public Socket clientSocket;
      private Handler handler_2;
      public DataInputStream in;
      public byte[] bytes = new byte[13];
      public Message msg;
      
      public Thread2(Socket clientSocket, Handler handler2) {
      this.clientSocket = clientSocket;
      this.handler_2 = handler2;
      }
      
       public void run() {
      
       while (!Thread.currentThread().isInterrupted()) {
      
          try {
      
              if (Looper.myLooper() == null) {
                  Looper.prepare();
              }
      
              this.in = new DataInputStream(clientSocket.getInputStream());
              in.readFully(bytes);
      
              if (in != null) {
                  for (int i = 0; i < bytes.length; i++){
                      Log.d("Data received", "valuewifi " + (0xFF & bytes[i]) );
                  }
      
                  msg = new Message();
                  Bundle b = new Bundle();
                  b.putByteArray("KEY", bytes);
                  msg.setData(b);
                  handler_2.sendMessage(msg);
              } else {
                  Thread1 = new Thread(new Thread1(handler_2,false));
                  Thread1.start();
                  return;
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      Looper.loop();
      }
      }
      }
      

现在的问题是: 我正确地从Raspberry Pi收到我的数据(每个包13个字节),确实:

Log.d("Data received", "valuewifi " + (0xFF & bytes[i]) );

正确打印我的值。然后我创建要发送到MainActivity中的处理程序的消息。 Bundle包含(我已验证)收到的输入流的相同值,但是在MainActivity的Handler中打印的消息:

Log.d("Data received", "value " + (0xFF & bytes[i]) );

替换每条消息的第一个字节值(我试图获得每个与RPi通信的2个包),其中66个实际上是&#34; B&#34;的ASCII码。我发送的信息是从Raspberry Pi开始发送数据。

请您知道为何会发生这种情况? 非常感谢您的帮助!:)

1 个答案:

答案 0 :(得分:0)

好吧,我已经在Thread2中找到了

public byte[] bytes = new byte[13];

之前的运行{..}内的

in.readFully(bytes);

信息的交换完美无缺。否则,我只在MainActivity中获取从服务器收到的最后一个字节包。

有关为何会发生的任何建议? 谢谢!