Android realizes TCP client, supports reading and writing

In the last chapter 14.Android - using sendMessage threads to communicate with each other We learned how to send data be...

In the last chapter 14.Android - using sendMessage threads to communicate with each other We learned how to send data between threads

Next, we will learn how to read and write TCP through socket

It should be noted that the socket must be written in the sub thread and cannot be used directly in the main ui thread, so we have created two class es here:

Mainactivity (main interface), tcpthread (get data received by socket)

Since the code has comments, it will not be interpreted

1.gif effect is as follows

2. Activity main.xml is as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/et_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:hint="Please fill in the content to be sent" /> <Button android:id="@+id/btn_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@+id/et_text" android:text="Send out" /> <TextView android:id="@+id/tv_recv" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/btn_send" android:minLines="20" android:hint="Content received" /> </RelativeLayout>

3.MainActivity.java is as follows

package com.example.tcpdemo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { TcpThread mt; TextView tv_recv; EditText et_text; //What to send Button btn_send; //Define a handler public Handler mHandler = new Handler() { public void handleMessage(Message msg) { //Print messages from the server System.out.println("read:"+msg.obj.toString()); tv_recv.append(msg.obj.toString()+"\r\n"); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_recv = (TextView)findViewById(R.id.tv_recv); et_text = (EditText)findViewById(R.id.et_text); mt = new TcpThread(); mt.setHandler(mHandler); //Set up handler mt.setIp("10.10.10.104"); //Set server address mt.start(); //Startup thread btn_send = (Button)findViewById(R.id.btn_send); btn_send.setOnClickListener(new OnClickListener() { //Send data to server public void onClick(View v) { if(!mt.write(et_text.getText().toString())) { Toast.makeText(getApplicationContext(), "fail in send", Toast.LENGTH_SHORT).show(); } } }); } }

4.TcpThread.java is as follows

package com.example.tcpdemo; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import android.os.Handler; import android.os.Message; public class TcpThread extends Thread { Handler mHandler=null; Socket socket = null; String ip = null; OutputStream outputStream = null; //Output stream InputStream inputStream=null; //Receiving flow //Get another thread's Handler public void setHandler( Handler handler){ mHandler = handler; } //Set up server IP public void setIp(String ip){ this.ip = ip; } public void run(){ try { socket = new Socket(ip, 8080); //Access the specified ip address:8080 } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Get output stream try { outputStream = socket.getOutputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ while (true) //Read the data sent from the server { final byte[] buffer = new byte[1024];//Create receive buffer inputStream = socket.getInputStream(); final int len = inputStream.read(buffer);//Read the data and return the length of the data if(len>0) { Message msg = mHandler.obtainMessage(); //Set what to send msg.obj = new String(buffer,0,len); mHandler.sendMessage(msg); } } } catch (IOException e) { } } //Write data to server public boolean write(String text){ boolean ret = true; try { outputStream.write(text.toString().getBytes()); } catch (IOException e) { ret = false; e.printStackTrace(); } return ret; } }

13 February 2020, 12:26 | Views: 5107

Add new comment

For adding a comment, please log in
or create account

0 comments