首页 > 代码库 > Android接收wifi路由器发送过来的一组字节数据

Android接收wifi路由器发送过来的一组字节数据

1、字节数组转换为字符串

byte[] byBuffer = new byte[20];
... ...
String strRead = new String(byBuffer);
strRead = String.copyValueOf(strRead.toCharArray(), 0, byBuffer.length]);

2、字符串转换成字节数组

byte[] byBuffer = new byte[200];
String strInput="abcdefg";
byBuffer= strInput.getBytes();

注意:如果字符串里面含有中文,要特别注意,在Android系统下,默认是UTF8编码,一个中文字符相当于3个字节,只有gb2312下一个中文相当于2字节。这种情况下可采取以下办法:

byte[] byBuffer = new byte[200];
String strInput="我是字符串";
byBuffer= strInput.getBytes("gb2312");

 

主界面代码

package my.work.Library;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;



public class WsnActivty extends Activity {
    /** Called when the activity is first created. */
    private Button btnNetwork;
    private String strIpAddr = null;
    static TextView textTips,seat;
    private ClientThread clientThread = null;
    private Message MainMsg;
    public static Handler mainHandler;
    static final int TIPS_UPDATE_UI = 3;   //tips_update_ui
    static final int SEAT_UPDATE_UI = 6;   //seat_update_ui
    
    static final int MAX_NODE = 4;
    static byte NodeData[][] = new byte[MAX_NODE][5];; // [5] 0=温度 1=湿度 2=气体 3=灯
    static final int RX_DATA_UPDATE_UI = 1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initControl();
        initMainHandler();
  
    }
    private void initControl() {
        // TODO Auto-generated method stub
          btnNetwork = (Button) findViewById(R.id.btn_network);
          btnNetwork.setOnClickListener(new ButtonClick());
          
          textTips = (TextView) findViewById(R.id.Tips);
            textTips.setText(R.string.init_tips);
            
           seat = (TextView) findViewById(R.id.statc001);
           seat.setText(R.string.people1);
        
    }
    class ButtonClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            
            switch (v.getId()) {
            case R.id.btn_network: // 连接网络
                showDialog(WsnActivty.this);
                break;
                }
   }
    }

            // 显示连接对话框
            private void showDialog(Context context) {
                final EditText editIP = new EditText(context);
                editIP.setText("192.168.0.10");

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                // builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("请输入服务器IP地址");
                builder.setView(editIP);
                builder.setPositiveButton("连接", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        strIpAddr = editIP.getText().toString();
                        boolean ret = isIPAddress(strIpAddr);

                        if (ret) {
                            textTips.setText("服务器IP地址:" + strIpAddr);
                        } else {
                            strIpAddr = null;
                            textTips.setText("IP地址不合法,请重新设置");
                            return;
                        }

                        clientThread = new ClientThread(strIpAddr);// 建立客户端线程
                        clientThread.start();

                        //mainTimer = new Timer();// 定时查询所有终端信息
                        //setTimerTask();
                    }
                });
                builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        if (clientThread != null) {
                            MainMsg = ClientThread.childHandler
                                    .obtainMessage(ClientThread.RX_EXIT);
                            ClientThread.childHandler.sendMessage(MainMsg);
                            textTips.setText("与服务器断开连接");
                        }
                    }
                });

                builder.show();
            }
        
        // 判断输入IP是否合法
        private boolean isIPAddress(String ipaddr) {
            boolean flag = false;
            Pattern pattern = Pattern
                    .compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");
            Matcher m = pattern.matcher(ipaddr);
            flag = m.matches();
            return flag;
        }
        
        void initMainHandler() {
            mainHandler = new Handler() {

                // 主线程消息处理中心
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                       case TIPS_UPDATE_UI:
                        String str = (String) msg.obj;  //连接成功
                        textTips.setText(str);
                        break;
                       case SEAT_UPDATE_UI:
                            String strseat = (String) msg.obj;  //连接成功
                            seat.setText(strseat);
                            break;
                    }
                    super.handleMessage(msg);
                }
            };
        }

}
    

子线程代码

package my.work.Library;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

public class ClientThread extends Thread {

    private OutputStream outputStream = null;
    private InputStream inputStream = null;
    private Socket socket;
    private SocketAddress socketAddress;
    public static Handler childHandler;
    private boolean RxFlag = true;
    final int TEXT_INFO = 12;
    static final int RX_EXIT = 11;
    static final int TX_DATA = http://www.mamicode.com/10;
    Context mainContext;
    Message msg;
    private String strIP;
    final int SERVER_PORT = 33333;
    byte cNodeData[][] = new byte[4][5]; // [5] 0=温度 1=湿度 2=气体 3=灯
    int RxCount = 0, nRecvLen, index = 0;
    byte CheckSum;
    // byte strRxBuf[] = new byte[256];
    int ucRecvLen = 7;
    
    private RxThread rxThread;

    //获取WsnActivty.java 开辟子线程clientThread对象线程传递过来的ip地址
    public ClientThread(String ip) {
        strIP = ip;
    }

    // 连接网络
    void connect() {
        RxFlag = true;
        socketAddress = new InetSocketAddress(strIP, SERVER_PORT);
        socket = new Socket();

        try {
            socket.connect(socketAddress, SERVER_PORT);
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();

            msg = WsnActivty.mainHandler.obtainMessage(
                    WsnActivty.TIPS_UPDATE_UI, "连接成功");
            WsnActivty.mainHandler.sendMessage(msg);
            
            
            rxThread = new RxThread();
            rxThread.start();

        } catch (IOException e) {
            try {
                sleep(10);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            msg = WsnActivty.mainHandler.obtainMessage(
                    WsnActivty.TIPS_UPDATE_UI, "无法连接到服务器");
            WsnActivty.mainHandler.sendMessage(msg);
            e.printStackTrace();
        } catch (NumberFormatException e) {

        }
    }

    void initChildHandler() {

        Looper.prepare(); // 在子线程中创建Handler必须初始化Looper

        childHandler = new Handler() {
            // 子线程消息处理中心
            public void handleMessage(Message msg) {

                // 接收主线程及其他线程的消息并处理...
                /**
                 * MainMsg = ClientThread.childHandler.obtainMessage(ClientThread.TX_DATA,
                 * len, 0, (Object) buffer);
                 * SendData(SendBuf, 7);
                 */
                switch (msg.what) {
                

                case RX_EXIT:
                    RxFlag = false;
                    try {
                        if (socket.isConnected()) {
                            inputStream.close();
                            outputStream.close();
                            socket.close();
                        }

                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                    childHandler.getLooper().quit();// 结束消息队列

                    break;

                default:
                    break;
                }

            }
        };

        // 启动该线程的消息队列
        Looper.loop();

    }

    public void run() {
        connect();
        initChildHandler();
        msg = WsnActivty.mainHandler.obtainMessage(WsnActivty.TIPS_UPDATE_UI,
                "与服务器断开连接");
        WsnActivty.mainHandler.sendMessage(msg);
    }
    
    // socket 接收线程
    public class RxThread extends Thread {
        public void run() {
            try {
                while (socket.isConnected() && RxFlag) {
                    byte strRxBuf[] = new byte[30];
                    byte i;
                    int RxIndex, len, readBytes = 0;
//                    msg = WsnActivty.mainHandler.obtainMessage(
//                            WsnActivty.SEAT_UPDATE_UI, "有人");
//                    WsnActivty.mainHandler.sendMessage(msg);
//                    
                    len = inputStream.read(strRxBuf, readBytes, ucRecvLen
                            - readBytes);

                    
                    
                    String strRead = new String(strRxBuf);
                    strRead = String.copyValueOf(strRead.toCharArray(), 0, strRxBuf.length);
                    
                    msg = WsnActivty.mainHandler.obtainMessage(
                            WsnActivty.SEAT_UPDATE_UI, strRead);
                    WsnActivty.mainHandler.sendMessage(msg);
                


                }
                if (socket.isConnected())
                    socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    byte GetDataLen(byte fc) {
        byte len = 0;

        switch (fc) {
        case 0x01:
            len = 22;
            break;
        case 0x07:
        case 0x08:
        case 0x0A:
        case 0x0B:
        case 0x0C:
        case 0x0D:
            len = 7;
            break;
        }

        return len;
    }
    

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
      <TextView 
          android:id="@+id/Tips"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/init_tips"
          android:textSize="40px"
          android:textColor="#00ff00"
          />
       <Button 
        android:id="@+id/btn_network" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/login"
        android:textSize="40px"
        android:textColor="#00ff00"
        />
       
       <TextView
        android:id="@+id/statc001" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
        android:textSize="40px"
        android:textColor="#00ff00"
        />
        <TextView
        android:id="@+id/statc002" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
        android:textSize="40px"
        android:textColor="#00ff00"
        />
                 <TextView
        android:id="@+id/statc003" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       
        android:textSize="40px"
        android:textColor="#00ff00"
        />
     <TextView
        android:id="@+id/statc004" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
        android:textSize="40px"
        android:textColor="#00ff00"
        />
      <TextView
        android:id="@+id/statc005" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
        android:textSize="40px"
        android:textColor="#00ff00"
        />
    
       
    
  
</LinearLayout>

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="login">连接服务器</string>
    <string name="app_name">梧州学院图书馆刷卡入座系统</string>
    <string name="move">获取视频流</string>
     <string name="init_tips">提示:请先打开WiFi或GPRS再连接网络</string>
     <string name="people1">空座</string>
     <string name="people2">有人</string>
   
    

</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="my.work.Library"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".WsnActivty"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
   
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

 

Android接收wifi路由器发送过来的一组字节数据