TCP / IP transmission (client) under Android platform

  In engineering projects, the transfer of information between embedded systems and software system or back-end database is a necessary way to achieve "Internet of Things", have been the simple concept of things, are usually in the form of a microcontroller / embedded the system for data collection and processing, wifi or ZigBee wireless module for transmission via Bluetooth, then the end of some software interacting with a computer to display data.

  For example, during a program, the need to obtain information on stm32 position, and then transmitted to the mobile device or computer terminal to display data, wifi chosen as the transmission medium, then we must consider the form of data transmission between the wifi or --TCP UDP transport.

  Simply record it in the actual development, to achieve and equipped with WIFI hardware system modules perform design and implementation of a program to communicate using TCP / IP protocol on the Android platform.

  A design interface, the EditText three, the Button two, there is a TextView for display; LinearLayout overall layout use (personal preference, clear structure)

  Procedures are as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:hint="IP地址"
            android:id="@+id/IPAddress"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <EditText
            android:hint="端口号"
            android:id="@+id/port"
            android:layout_weight="2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/connect"
        android:text="开始连接"
        />
    <EditText
        android:hint="输入需要发送的信息"
        android:id="@+id/sendData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/send"
        android:text="Data transmission " =" the wrap_content "
        Android: layout_width

    <


        android:layout_height="wrap_content" />

    <TextView
        android:background="#eeeeee"
        android:id="@+id/information"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

  Implement a general interface, as follows:

  Next is a functional section implemented in the network connection TCP / IP protocol, two main information: IP address and port number.

  In JAVA environment, TCP connection is relatively simple, and this is one advantage of JAVA:

  Socket socket=new Socket(IP_Address,Port);

  A simple phrase can achieve network connection.

  BufferedReader and a need to achieve a PrintWriter data transmission, when the operation is completed Socket, setting them:

mBufferedReaderClient = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
mPrintWriterClient = new PrintWriter(mSocket.getOutputStream(),true);

  Then open up other threads to achieve transmission as well as some updated view of the data.

  java part of the code as follows:

package com.example.hp.acceleration;

import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private Button mButtonConnect;
    private Button mButtonSend;
    private TextView mTextViewMessage;
    private boolean isConnect;
    private String Information;
    private EditText mEditTextIP;
    private EditText mEditTextPort;
    private EditText mEditTextSendData;

    private Socket mSocket=null;
    private BufferedReader mBufferedReaderClient=null;
    private PrintWriter mPrintWriterClient=null;


    private String IP="";
    private int port;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()//磁盘读取操作
                .detectDiskWrites()//磁盘写入操作
                .detectNetwork () // network operation 
                .penaltyLog () // print exception information in violation Logcat in 
                .build ()); 
        StrictMode.setVmPolicy ( new new StrictMode.VmPolicy.Builder () 
                .detectLeakedSqlLiteObjects () // leaked SqLite objects 
                . penaltyLog () 
                .penaltyDeath () 
                .build ()); 

        mButtonConnect = (the Button) the findViewById (R.id.connect); 
        mButtonSend = (the Button) the findViewById (R.id.send); 
        mTextViewMessage = (the TextView) the findViewById (R & lt. id.information); 
        mEditTextIP =(EditText)findViewById(R.id.IPAddress);
        mEditTextPort=(EditText)findViewById(R.id.port);
        mEditTextSendData=(EditText)findViewById(R.id.sendData);

        mTextViewMessage.setMovementMethod(ScrollingMovementMethod.getInstance());
        mTextViewMessage.setTextIsSelectable(true);

        isConnect=false;
        mButtonSend.setEnabled(false);


        mButtonConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isConnect)
                {
                    isConnect=false;
                    mButtonConnect.setText("开始连接");
                    mButtonSend.setEnabled(false);
                    mTextViewMessage.setText("");
                    if(mSocket!=null) {
                        try {
                            mSocket.close();
                        } catch (IOException e) {

                        }
                    }
                }else{
                    isConnect=true;
                    mButtonConnect.setText("断开连接");

                        mButtonSend.setEnabled(true);
                        IP=mEditTextIP.getText().toString();
                        String portString=mEditTextPort.getText().toString();
                        if (portString.length()>1){
                            port=Integer.valueOf(portString);
                        }
                        Thread thread=new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    mSocket=new Socket(IP,port);
                                    mBufferedReaderClient = new BufferedReader(new InputStreamReader
                                            (mSocket.getInputStream()));
                                    mPrintWriterClient = new PrintWriter(mSocket.getOutputStream(),
                                            true);
                                    Message msg=new Message();
                                    msg.what=0;
                                    mHandler.sendMessage(msg);
                                }catch (IOException e) {
                                    mTextViewMessage.setText("error");
                                }
                                char[] buffer=new char[256];
                                int num=0;
                                while (isConnect)
                                {
                                    try{
                                        if ((num=mBufferedReaderClient.read(buffer))>0) {
                                            Information=getInfoBuff(buffer,num);
                                            Message msg=new Message();
                                            msg.what=1;
                                            mHandler.sendMessage(msg);
                                        }
                                    }catch (Exception e) {
                                    }
                                }

                            }
                        });
                        if (IP.length()>1&&portString.length()>=1)
                        {
                            thread.start();
                        }else
                        {
                            mTextViewMessage.setText("IP地址错误或端口号错误");
                        }

                }
                }
        });


        mButtonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Thread thread=new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String string=mEditTextSendData.getText().toString();
                            mPrintWriterClient.print(string);
                            mPrintWriterClient.flush();
                        }catch (Exception e){
                        }
                    }
                });
                thread.start();
            }
        });


    }
    private String getInfoBuff(char[] buff,int count){
        char[] temp=new char[count];
        for(int i=0;i<count;i++){
            temp[i]=buff[i];
        }
        return new String(temp);
    }


    Handler mHandler=new Handler(){
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            if (msg.what==0){
                Toast.makeText(MainActivity.this,"连接成功!",Toast.LENGTH_SHORT).show();
            }
            else if (msg.what==1){
                mTextViewMessage.append(Information+"\r\n");

            }
        }
    };

}

  Finally, in the Android environment, we need to give permission in AndroidManifest.xml file

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

  Permissions are more than a few Android wifi use several communication must be under the TCP protocol.

 

Guess you like

Origin www.cnblogs.com/greed-is-good/p/10946494.html